Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: core pkg uses slog #410

Merged
merged 17 commits into from Dec 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 3 additions & 8 deletions cli/root.go
Expand Up @@ -23,7 +23,6 @@ import (
"github.com/spf13/cobra"
"github.com/yomorun/yomo/cli/serverless"
"github.com/yomorun/yomo/pkg/file"
"github.com/yomorun/yomo/pkg/logger"
)

var (
Expand All @@ -35,13 +34,9 @@ var (

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "yomo",
Version: GetVersion(),
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if verbose {
logger.EnableDebug()
}
},
Use: "yomo",
Version: GetVersion(),
PersistentPreRun: func(cmd *cobra.Command, args []string) {},
// Run: func(cmd *cobra.Command, args []string) { },
}

Expand Down
41 changes: 22 additions & 19 deletions core/client.go
Expand Up @@ -12,9 +12,9 @@ import (

"github.com/lucas-clemente/quic-go"
"github.com/yomorun/yomo/core/frame"
"github.com/yomorun/yomo/core/log"
"github.com/yomorun/yomo/core/yerr"
"github.com/yomorun/yomo/pkg/id"
"golang.org/x/exp/slog"
)

// ClientOption YoMo client options
Expand All @@ -37,7 +37,7 @@ type Client struct {
mu sync.Mutex
opts *clientOptions
localAddr string // client local addr, it will be changed on reconnect
logger log.Logger
logger *slog.Logger
errc chan error
}

Expand All @@ -48,15 +48,18 @@ func NewClient(appName string, connType ClientType, opts ...ClientOption) *Clien
for _, o := range opts {
o(option)
}
clientID := id.New()

logger := option.logger.With("component", "client", "client_type", connType.String(), "client_id", clientID, "client_name", appName)

return &Client{
name: appName,
clientID: id.New(),
clientID: clientID,
clientType: connType,
state: ConnStateReady,
opts: option,
errc: make(chan error),
logger: option.logger,
logger: logger,
}
}

Expand Down Expand Up @@ -121,12 +124,12 @@ func (c *Client) connect(ctx context.Context, addr string) error {
c.state = ConnStateConnected
c.localAddr = c.conn.LocalAddr().String()

c.logger.Printf("%s❤️ [%s][%s](%s) is connected to YoMo-Zipper %s", ClientLogPrefix, c.name, c.clientID, c.localAddr, addr)
c.logger.Debug("connected to YoMo-Zipper")

// receiving frames
go func() {
closeConn, closeClient, err := c.handleFrame()
c.logger.Debugf("%shandleFrame: %v, %v, %T, %v", ClientLogPrefix, closeConn, closeClient, err, err)
c.logger.Debug("connected to YoMo-Zipper", "close_conn", closeConn, "close_client", closeClient, "error", err)

c.mu.Lock()
defer c.mu.Unlock()
Expand Down Expand Up @@ -164,7 +167,7 @@ func (c *Client) handleFrame() (bool, bool, error) {
if err == io.EOF {
return true, false, err
} else if strings.HasPrefix(err.Error(), "unknown frame type") {
c.logger.Warnf("%s%v", ClientLogPrefix, err)
c.logger.Warn("unknown frame type", "error", err)
continue
} else if e, ok := err.(*quic.IdleTimeoutError); ok {
return false, false, e
Expand All @@ -179,7 +182,7 @@ func (c *Client) handleFrame() (bool, bool, error) {
// read frame
// first, get frame type
frameType := f.Type()
c.logger.Debugf("%shandleFrame: %v", ClientLogPrefix, frameType)
c.logger.Debug("handleFrame", "frame_type", frameType)
switch frameType {
case frame.TagOfRejectedFrame:
if v, ok := f.(*frame.RejectedFrame); ok {
Expand All @@ -192,21 +195,21 @@ func (c *Client) handleFrame() (bool, bool, error) {
case frame.TagOfDataFrame: // DataFrame carries user's data
if v, ok := f.(*frame.DataFrame); ok {
if c.processor == nil {
c.logger.Warnf("%sprocessor is nil", ClientLogPrefix)
c.logger.Warn("processor is nil")
} else {
c.processor(v)
}
}
case frame.TagOfBackflowFrame:
if v, ok := f.(*frame.BackflowFrame); ok {
if c.receiver == nil {
c.logger.Warnf("%sreceiver is nil", ClientLogPrefix)
c.logger.Warn("receiver is nil")
} else {
c.receiver(v)
}
}
default:
c.logger.Warnf("%sunknown or unsupported frame %#x", ClientLogPrefix, frameType)
c.logger.Warn("unknown or unsupported frame", "frame_type", frameType)
}
}
}
Expand All @@ -228,7 +231,7 @@ func (c *Client) Close() error {
}

func (c *Client) close() error {
c.logger.Printf("%s💔 close the connection, name:%s, id:%s, addr:%s", ClientLogPrefix, c.name, c.clientID, c.addr)
c.logger.Info("close the connection")

// close error channel so that close handler function will be called
close(c.errc)
Expand All @@ -239,7 +242,7 @@ func (c *Client) close() error {

// WriteFrame writes a frame to the connection, gurantee threadsafe.
func (c *Client) WriteFrame(frm frame.Frame) error {
c.logger.Debugf("%s[%s](%s)@%s WriteFrame() will write frame: %s", ClientLogPrefix, c.name, c.localAddr, c.State(), frm.Type())
c.logger.Debug("close the connection", "client_state", c.State(), "frame_type", frm.Type().String())

if c.state != ConnStateConnected {
return errors.New("client connection isn't connected")
Expand All @@ -255,13 +258,13 @@ func (c *Client) WriteFrame(frm frame.Frame) error {
// SetDataFrameObserver sets the data frame handler.
func (c *Client) SetDataFrameObserver(fn func(*frame.DataFrame)) {
c.processor = fn
c.logger.Debugf("%sSetDataFrameObserver(%v)", ClientLogPrefix, c.processor)
c.logger.Debug("SetDataFrameObserver")
}

// SetBackflowFrameObserver sets the backflow frame handler.
func (c *Client) SetBackflowFrameObserver(fn func(*frame.BackflowFrame)) {
c.receiver = fn
c.logger.Debugf("%sSetBackflowFrameObserver(%v)", ClientLogPrefix, c.receiver)
c.logger.Debug("SetBackflowFrameObserver")
}

// reconnect the connection between client and server.
Expand All @@ -272,7 +275,7 @@ func (c *Client) reconnect(ctx context.Context, addr string) {
for {
select {
case <-ctx.Done():
c.logger.Debugf("%s[%s](%s) context.Done()", ClientLogPrefix, c.name, c.localAddr)
c.logger.Debug("context.Done", "error", ctx.Err())
return
case err, ok := <-c.errc:
if c.errorfn != nil && err != nil {
Expand All @@ -287,10 +290,10 @@ func (c *Client) reconnect(ctx context.Context, addr string) {
state := c.state
c.mu.Unlock()
if state == ConnStateDisconnected {
c.logger.Printf("%s[%s][%s](%s) is reconnecting to YoMo-Zipper %s...", ClientLogPrefix, c.name, c.clientID, c.localAddr, addr)
c.logger.Info("reconnecting to YoMo-Zipper")
err := c.connect(ctx, addr)
if err != nil {
c.logger.Errorf("%s[%s][%s](%s) reconnect error:%v", ClientLogPrefix, c.name, c.clientID, c.localAddr, err)
c.logger.Error("reconnecting to YoMo-Zipper", err)
}
}
}
Expand All @@ -307,7 +310,7 @@ func (c *Client) SetObserveDataTags(tag ...frame.Tag) {
}

// Logger get client's logger instance, you can customize this using `yomo.WithLogger`
func (c *Client) Logger() log.Logger {
func (c *Client) Logger() *slog.Logger {
return c.logger
}

Expand Down
12 changes: 6 additions & 6 deletions core/client_options.go
Expand Up @@ -7,9 +7,9 @@ import (
"github.com/lucas-clemente/quic-go"
"github.com/yomorun/yomo/core/auth"
"github.com/yomorun/yomo/core/frame"
"github.com/yomorun/yomo/core/log"
"github.com/yomorun/yomo/pkg/logger"
"github.com/yomorun/yomo/core/ylog"
pkgtls "github.com/yomorun/yomo/pkg/tls"
"golang.org/x/exp/slog"
)

// clientOptions are the options for YoMo client.
Expand All @@ -18,11 +18,11 @@ type clientOptions struct {
quicConfig *quic.Config
tlsConfig *tls.Config
credential *auth.Credential
logger log.Logger
logger *slog.Logger
}

func defaultClientOption() *clientOptions {
logger := logger.Default()
logger := ylog.Default()

defalutQuicConfig := &quic.Config{
Versions: []quic.VersionNumber{quic.Version2},
Expand All @@ -45,7 +45,7 @@ func defaultClientOption() *clientOptions {
}

if opts.credential != nil {
logger.Printf("%suse credential: [%s]", ClientLogPrefix, opts.credential.Name())
logger.Info("use credential", "component", "client", "credential_name", opts.credential.Name())
}

return opts
Expand Down Expand Up @@ -82,7 +82,7 @@ func WithClientQuicConfig(qc *quic.Config) ClientOption {
}

// WithLogger sets logger for the client.
func WithLogger(logger log.Logger) ClientOption {
func WithLogger(logger *slog.Logger) ClientOption {
return func(o *clientOptions) {
o.logger = logger
}
Expand Down
4 changes: 2 additions & 2 deletions core/client_test.go
Expand Up @@ -12,8 +12,8 @@ import (
"github.com/yomorun/yomo/core/frame"
"github.com/yomorun/yomo/core/metadata"
"github.com/yomorun/yomo/core/router"
"github.com/yomorun/yomo/core/ylog"
"github.com/yomorun/yomo/pkg/config"
"github.com/yomorun/yomo/pkg/logger"
)

const testaddr = "127.0.0.1:19999"
Expand Down Expand Up @@ -64,7 +64,7 @@ func TestFrameRoundTrip(t *testing.T) {
WithObserveDataTags(obversedTag),
WithClientQuicConfig(DefalutQuicConfig),
WithClientTLSConfig(nil),
WithLogger(logger.Default()),
WithLogger(ylog.Default()),
)

source.SetBackflowFrameObserver(func(bf *frame.BackflowFrame) {
Expand Down
16 changes: 13 additions & 3 deletions core/connection.go
Expand Up @@ -6,7 +6,7 @@ import (

"github.com/yomorun/yomo/core/frame"
"github.com/yomorun/yomo/core/metadata"
"github.com/yomorun/yomo/pkg/logger"
"golang.org/x/exp/slog"
)

// Connection wraps the specific io connections (typically quic.Connection) to transfer y3 frames
Expand Down Expand Up @@ -36,9 +36,19 @@ type connection struct {
observed []frame.Tag // observed data tags
mu sync.Mutex
closed bool
logger *slog.Logger
}

func newConnection(name string, clientID string, clientType ClientType, metadata metadata.Metadata, stream io.ReadWriteCloser, observed []frame.Tag) Connection {
func newConnection(
name string,
clientID string,
clientType ClientType,
metadata metadata.Metadata,
stream io.ReadWriteCloser,
observed []frame.Tag,
logger *slog.Logger,
) Connection {
logger.Debug("new connecton")
return &connection{
name: name,
clientID: clientID,
Expand Down Expand Up @@ -82,7 +92,7 @@ func (c *connection) Write(f frame.Frame) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
logger.Warnf("%sclient stream is closed: %s", ServerLogPrefix, c.clientID)
c.logger.Warn("client stream is closed")
return nil
}
_, err := c.stream.Write(f.Encode())
Expand Down
13 changes: 7 additions & 6 deletions core/connector.go
Expand Up @@ -4,7 +4,7 @@ import (
"sync"

"github.com/yomorun/yomo/core/frame"
"github.com/yomorun/yomo/pkg/logger"
"golang.org/x/exp/slog"
)

var _ Connector = &connector{}
Expand All @@ -26,22 +26,23 @@ type Connector interface {
}

type connector struct {
conns sync.Map
conns sync.Map
logger *slog.Logger
}

func newConnector() Connector {
return &connector{conns: sync.Map{}}
func newConnector(logger *slog.Logger) Connector {
return &connector{conns: sync.Map{}, logger: logger}
}

// Add a connection.
func (c *connector) Add(connID string, conn Connection) {
logger.Debugf("%sconnector add: connID=%s", ServerLogPrefix, connID)
c.logger.Debug("connector add connection", "conn_id", connID)
c.conns.Store(connID, conn)
}

// Remove a connection.
func (c *connector) Remove(connID string) {
logger.Debugf("%sconnector remove: connID=%s", ServerLogPrefix, connID)
c.logger.Debug("connector remove connection", "conn_id", connID)
c.conns.Delete(connID)
}

Expand Down