-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
123 lines (102 loc) · 2.56 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package unix
import (
"context"
"errors"
"io"
"net"
"time"
"github.com/dolfly/core/chain"
"github.com/dolfly/core/handler"
"github.com/dolfly/core/hop"
"github.com/dolfly/core/logger"
md "github.com/dolfly/core/metadata"
xnet "github.com/dolfly/x/internal/net"
"github.com/dolfly/x/registry"
)
func init() {
registry.HandlerRegistry().Register("unix", NewHandler)
}
type unixHandler struct {
hop hop.Hop
router *chain.Router
md metadata
options handler.Options
}
func NewHandler(opts ...handler.Option) handler.Handler {
options := handler.Options{}
for _, opt := range opts {
opt(&options)
}
return &unixHandler{
options: options,
}
}
func (h *unixHandler) Init(md md.Metadata) (err error) {
if err = h.parseMetadata(md); err != nil {
return
}
h.router = h.options.Router
if h.router == nil {
h.router = chain.NewRouter(chain.LoggerRouterOption(h.options.Logger))
}
return
}
// Forward implements handler.Forwarder.
func (h *unixHandler) Forward(hop hop.Hop) {
h.hop = hop
}
func (h *unixHandler) Handle(ctx context.Context, conn net.Conn, opts ...handler.HandleOption) error {
defer conn.Close()
log := h.options.Logger
log = log.WithFields(map[string]any{
"remote": conn.RemoteAddr().String(),
"local": conn.LocalAddr().String(),
})
if h.hop != nil {
target := h.hop.Select(ctx)
if target == nil {
err := errors.New("target not available")
log.Error(err)
return err
}
log = log.WithFields(map[string]any{
"node": target.Name,
"dst": target.Addr,
})
return h.forwardUnix(ctx, conn, target, log)
}
cc, err := h.router.Dial(ctx, "tcp", "@")
if err != nil {
log.Error(err)
return err
}
defer cc.Close()
t := time.Now()
log.Infof("%s <-> %s", conn.LocalAddr(), "@")
xnet.Transport(conn, cc)
log.WithFields(map[string]any{
"duration": time.Since(t),
}).Infof("%s >-< %s", conn.LocalAddr(), "@")
return nil
}
func (h *unixHandler) forwardUnix(ctx context.Context, conn net.Conn, target *chain.Node, log logger.Logger) (err error) {
log.Debugf("%s >> %s", conn.LocalAddr(), target.Addr)
var cc io.ReadWriteCloser
if opts := h.router.Options(); opts != nil && opts.Chain != nil {
cc, err = h.router.Dial(ctx, "unix", target.Addr)
} else {
cc, err = (&net.Dialer{}).DialContext(ctx, "unix", target.Addr)
}
if err != nil {
log.Error(err)
return err
}
defer cc.Close()
t := time.Now()
log.Infof("%s <-> %s", conn.LocalAddr(), target.Addr)
xnet.Transport(conn, cc)
log.WithFields(map[string]any{
"duration": time.Since(t),
}).Infof("%s >-< %s", conn.LocalAddr(), target.Addr)
return nil
}