feat: 重构事件处理,添加默认通道和发布逻辑,移除不必要的提供者

This commit is contained in:
Rogee
2025-09-11 14:51:40 +08:00
parent ced4202dc9
commit c0d8f070e4
14 changed files with 266 additions and 193 deletions

View File

@@ -2,10 +2,13 @@ package cmux
import (
"fmt"
"net"
"time"
"{{.ModuleName}}/providers/grpc"
"{{.ModuleName}}/providers/http"
log "github.com/sirupsen/logrus"
"github.com/soheilhy/cmux"
"go.ipao.vip/atom/container"
"go.ipao.vip/atom/opt"
@@ -39,23 +42,68 @@ type CMux struct {
Http *http.Service
Grpc *grpc.Grpc
Mux cmux.CMux
Base net.Listener
}
func (c *CMux) Serve() error {
// grpcL := c.Mux.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
// httpL := c.Mux.Match(cmux.HTTP1Fast())
// httpL := c.Mux.Match(cmux.Any())
// Protect against slowloris connections when sniffing protocol
// Safe even if SetReadTimeout is a no-op in the cmux version in use
c.Mux.SetReadTimeout(1 * time.Second)
addr := ""
if c.Base != nil && c.Base.Addr() != nil {
addr = c.Base.Addr().String()
}
log.WithFields(log.Fields{
"addr": addr,
}).Info("cmux starting")
// Route classic HTTP/1.x traffic to the HTTP service
httpL := c.Mux.Match(cmux.HTTP1Fast())
grpcL := c.Mux.Match(cmux.Any())
// Route gRPC (HTTP/2 with content-type application/grpc) to the gRPC service.
// Additionally, send other HTTP/2 traffic to gRPC since Fiber (HTTP) does not serve HTTP/2.
grpcL := c.Mux.Match(
cmux.HTTP2HeaderField("content-type", "application/grpc"),
cmux.HTTP2(),
)
var eg errgroup.Group
eg.Go(func() error {
return c.Grpc.ServeWithListener(grpcL)
log.WithField("addr", addr).Info("grpc serving via cmux")
err := c.Grpc.ServeWithListener(grpcL)
if err != nil {
log.WithError(err).Error("grpc server exited with error")
} else {
log.Info("grpc server exited")
}
return err
})
eg.Go(func() error {
return c.Http.Listener(httpL)
log.WithField("addr", addr).Info("http serving via cmux")
err := c.Http.Listener(httpL)
if err != nil {
log.WithError(err).Error("http server exited with error")
} else {
log.Info("http server exited")
}
return err
})
return c.Mux.Serve()
// Run cmux dispatcher; wait for the first error from any goroutine
eg.Go(func() error {
err := c.Mux.Serve()
if err != nil {
log.WithError(err).Error("cmux exited with error")
} else {
log.Info("cmux exited")
}
return err
})
err := eg.Wait()
if err == nil {
log.Info("cmux and sub-servers exited cleanly")
}
return err
}

View File

@@ -23,10 +23,15 @@ func Provide(opts ...opt.Option) error {
return nil, err
}
return &CMux{
mux := &CMux{
Http: http,
Grpc: grpc,
Mux: cmux.New(l),
}, nil
Base: l,
}
// Ensure cmux stops accepting new connections on shutdown
container.AddCloseAble(func() { _ = l.Close() })
return mux, nil
}, o.DiOptions()...)
}