chore: moved packages to v1
This commit is contained in:
1 parent
522ba1b639
commit
43e3a8a397
15 files changed
+26
-14
No files matched your search
@@ -0,0 +1,191 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
mcontext "github.com/abelith/gomax/v1/context"
|
||||
"github.com/abelith/gomax/v1/state"
|
||||
"github.com/abelith/gomax/v1/state/memory"
|
||||
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 = 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)
|
||||
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) 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)
|
||||
<-ctx.Done()
|
||||
d.wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Dispatcher) handleUpdates(ch <-chan model.Update) {
|
||||
for upd := range ch {
|
||||
d.wg.Go(func() {
|
||||
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(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)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package core
|
||||
|
||||
import "fmt"
|
||||
|
||||
var (
|
||||
ErrRouteNotFound = fmt.Errorf("route not foun")
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
package core
|
||||
|
||||
import mcontext "github.com/abelith/gomax/v1/context"
|
||||
|
||||
type HandlerFunc func(c *mcontext.Context) error
|
||||
|
||||
func (h HandlerFunc) HandleUpdate(c *mcontext.Context) error {
|
||||
return h(c)
|
||||
}
|
||||
|
||||
func (h HandlerFunc) Use(_ ...Middleware) {
|
||||
panic("HandlerFunc.Use must never be called")
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
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"
|
||||
"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{}
|
||||
|
||||
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 {
|
||||
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 <-ctx.Done():
|
||||
return
|
||||
case ch <- update:
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func (tp *TestPoller) Start(_ context.Context) (<-chan model.Update, error) {
|
||||
return nil, fmt.Errorf("unimplemented")
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
mcontext "github.com/abelith/gomax/v1/context"
|
||||
)
|
||||
|
||||
type Middleware func(next HandlerFunc) HandlerFunc
|
||||
|
||||
type route struct {
|
||||
h UpdateHandler
|
||||
filters []func(c *mcontext.Context) bool
|
||||
}
|
||||
|
||||
type Router struct {
|
||||
routes []route
|
||||
mw []Middleware
|
||||
}
|
||||
|
||||
func (r *Router) HandleUpdate(c *mcontext.Context) error {
|
||||
var current HandlerFunc = r.dispatch
|
||||
|
||||
for i := len(r.mw) - 1; i >= 0; i-- {
|
||||
current = r.mw[i](current)
|
||||
}
|
||||
|
||||
return current.HandleUpdate(c)
|
||||
}
|
||||
|
||||
func (r *Router) Use(mws ...Middleware) {
|
||||
r.mw = append(r.mw, mws...)
|
||||
}
|
||||
|
||||
func (r *Router) HandleFunc(h HandlerFunc, filters ...func(c *mcontext.Context) bool) {
|
||||
r.routes = append(r.routes, route{
|
||||
h: h,
|
||||
filters: filters,
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Router) Handle(h UpdateHandler, filters ...func(c *mcontext.Context) bool) {
|
||||
r.routes = append(r.routes, route{
|
||||
h: h,
|
||||
filters: filters,
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Router) dispatch(c *mcontext.Context) error {
|
||||
for _, rt := range r.routes {
|
||||
if match(rt.filters, c) {
|
||||
err := rt.h.HandleUpdate(c)
|
||||
if errors.Is(err, ErrRouteNotFound) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return ErrRouteNotFound
|
||||
}
|
||||
|
||||
func match(filters []func(c *mcontext.Context) bool, c *mcontext.Context) bool {
|
||||
for _, filter := range filters {
|
||||
if !filter(c) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
Reference in new issue
Block a user