-
Notifications
You must be signed in to change notification settings - Fork 20
/
wire.go
184 lines (153 loc) · 4.34 KB
/
wire.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package wire
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log/slog"
"net"
"sync"
"sync/atomic"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jeroenrinzema/psql-wire/pkg/buffer"
"github.com/jeroenrinzema/psql-wire/pkg/types"
)
// ListenAndServe opens a new Postgres server using the given address and
// default configurations. The given handler function is used to handle simple
// queries. This method should be used to construct a simple Postgres server for
// testing purposes or simple use cases.
func ListenAndServe(address string, handler ParseFn) error {
server, err := NewServer(handler)
if err != nil {
return err
}
return server.ListenAndServe(address)
}
// NewServer constructs a new Postgres server using the given address and server options.
func NewServer(parse ParseFn, options ...OptionFn) (*Server, error) {
srv := &Server{
parse: parse,
logger: slog.Default(),
closer: make(chan struct{}),
types: pgtype.NewMap(),
Statements: DefaultStatementCacheFn,
Portals: DefaultPortalCacheFn,
Session: func(ctx context.Context) (context.Context, error) { return ctx, nil },
}
for _, option := range options {
err := option(srv)
if err != nil {
return nil, fmt.Errorf("unexpected error while attempting to configure a new server: %w", err)
}
}
return srv, nil
}
// Server contains options for listening to an address.
type Server struct {
closing atomic.Bool
wg sync.WaitGroup
logger *slog.Logger
types *pgtype.Map
Auth AuthStrategy
BufferedMsgSize int
Parameters Parameters
TLSConfig *tls.Config
parse ParseFn
Session SessionHandler
Statements func() StatementCache
Portals func() PortalCache
CloseConn CloseFn
TerminateConn CloseFn
Version string
closer chan struct{}
}
// ListenAndServe opens a new Postgres server on the preconfigured address and
// starts accepting and serving incoming client connections.
func (srv *Server) ListenAndServe(address string) error {
listener, err := net.Listen("tcp", address)
if err != nil {
return err
}
return srv.Serve(listener)
}
// Serve accepts and serves incoming Postgres client connections using the
// preconfigured configurations. The given listener will be closed once the
// server is gracefully closed.
func (srv *Server) Serve(listener net.Listener) error {
defer srv.logger.Info("closing server")
srv.logger.Info("serving incoming connections", slog.String("addr", listener.Addr().String()))
srv.wg.Add(1)
// NOTE: handle graceful shutdowns
go func() {
defer srv.wg.Done()
<-srv.closer
err := listener.Close()
if err != nil {
srv.logger.Error("unexpected error while attempting to close the net listener", "err", err)
}
}()
for {
conn, err := listener.Accept()
if errors.Is(err, net.ErrClosed) {
return nil
}
if err != nil {
return err
}
go func() {
ctx := context.Background()
err = srv.serve(ctx, conn)
if err != nil {
srv.logger.Error("an unexpected error got returned while serving a client connection", "err", err)
}
}()
}
}
func (srv *Server) serve(ctx context.Context, conn net.Conn) error {
ctx = setTypeInfo(ctx, srv.types)
ctx = setRemoteAddress(ctx, conn.RemoteAddr())
defer conn.Close()
srv.logger.Debug("serving a new client connection")
conn, version, reader, err := srv.Handshake(conn)
if err != nil {
return err
}
if version == types.VersionCancel {
return conn.Close()
}
srv.logger.Debug("handshake successfull, validating authentication")
writer := buffer.NewWriter(srv.logger, conn)
ctx, err = srv.readClientParameters(ctx, reader)
if err != nil {
return err
}
ctx, err = srv.handleAuth(ctx, reader, writer)
if err != nil {
return err
}
srv.logger.Debug("connection authenticated, writing server parameters")
ctx, err = srv.writeParameters(ctx, writer, srv.Parameters)
if err != nil {
return err
}
ctx, err = srv.Session(ctx)
if err != nil {
return err
}
session := &Session{
Server: srv,
Statements: srv.Statements(),
Portals: srv.Portals(),
}
return session.consumeCommands(ctx, conn, reader, writer)
}
// Close gracefully closes the underlaying Postgres server.
func (srv *Server) Close() error {
if srv.closing.Load() {
return nil
}
srv.closing.Store(true)
close(srv.closer)
srv.wg.Wait()
return nil
}