forked from panoplyio/pgsrv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.go
271 lines (241 loc) · 6.73 KB
/
session.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package pgsrv
import (
"context"
"fmt"
"github.com/jackc/pgx/pgproto3"
"github.com/jackc/pgx/pgtype"
parser "github.com/lfittl/pg_query_go"
nodes "github.com/lfittl/pg_query_go/nodes"
"github.com/panoplyio/pgsrv/protocol"
"io"
"math/rand"
"strings"
"sync"
)
var allSessions sync.Map
type portal struct {
srcPreparedStatement string
parameters [][]byte
}
// Session represents a single client-connection, and handles all of the
// communications with that client.
//
// see: https://www.postgresql.org/docs/9.2/static/protocol.html
// for postgres protocol and startup handshake process
type session struct {
Server *server
Conn io.ReadWriteCloser
ConnInfo *pgtype.ConnInfo
Args map[string]interface{}
Secret int32 // used for cancelling requests
Ctx context.Context
CancelFunc context.CancelFunc
initialized bool
stmts map[string]*nodes.PrepareStmt
pendingStmts map[string]*nodes.PrepareStmt
portals map[string]*portal
}
func (s *session) startUp() error {
handshake := protocol.NewHandshake(s.Conn)
msg, err := handshake.Init()
if err != nil {
return err
}
if msg.IsCancel() {
pid, secret, err := msg.CancelKeyData()
if err != nil {
return err
}
s, ok := allSessions.Load(pid)
if !ok || s == nil {
_, cancelFunc := context.WithCancel(context.Background())
cancelFunc()
} else if s.(*session).Secret == secret {
s.(*session).CancelFunc() // intentionally doesn't report success to frontend
}
return nil // disconnect.
}
s.Args, err = msg.StartupArgs()
if err != nil {
return err
}
// handle authentication
err = s.Server.authenticator.authenticate(handshake, s.Args)
if err != nil {
return err
}
err = handshake.Write(protocol.ParameterStatus("client_encoding", "utf8"))
if err != nil {
return err
}
// generate cancellation pid and secret for this session
s.Secret = rand.Int31()
pid := rand.Int31()
for s1, ok := allSessions.Load(pid); ok && s1 != nil; pid++ {
s1, ok = allSessions.Load(pid)
}
allSessions.Store(pid, s)
defer allSessions.Delete(pid)
// notify the client of the pid and secret to be passed back when it wishes
// to interrupt this session
s.Ctx, s.CancelFunc = context.WithCancel(context.Background())
err = handshake.Write(protocol.BackendKeyData(pid, s.Secret))
if err != nil {
return err
}
s.ConnInfo = pgtype.NewConnInfo()
for k, v := range protocol.TypesOid {
s.ConnInfo.RegisterDataType(pgtype.DataType{Name: strings.ToLower(k), OID: pgtype.OID(v), Value: &pgtype.GenericText{}})
}
return nil
}
// Handle a connection session
func (s *session) Serve() error {
err := s.startUp()
if err != nil {
return err
}
s.stmts = map[string]*nodes.PrepareStmt{}
s.pendingStmts = map[string]*nodes.PrepareStmt{}
s.portals = map[string]*portal{}
t := protocol.NewTransport(s.Conn)
// query-cycle
for {
msg, ts, err := t.NextFrontendMessage()
if err != nil {
return err
}
s.handleTransactionState(ts)
err = s.handleFrontendMessage(t, msg)
if err != nil {
return err
}
}
}
func (s *session) handleFrontendMessage(t *protocol.Transport, msg pgproto3.FrontendMessage) (err error) {
var res []protocol.Message
switch v := msg.(type) {
case *pgproto3.Terminate:
s.Conn.Close()
return nil // client terminated intentionally
case *pgproto3.Query:
q := &query{
transport: t,
sql: v.String,
queryer: s.Server,
execer: s.Server,
}
err = q.Run(s)
case *pgproto3.Describe:
res, err = s.describe(v)
case *pgproto3.Parse:
res, err = s.prepare(v)
case *pgproto3.Bind:
res, err = s.bind(v)
case *pgproto3.Sync:
default:
res = append(res, protocol.ErrorResponse(Unsupported("message type")))
}
for _, m := range res {
err = t.Write(m)
if err != nil {
break
}
}
return
}
func (s *session) handleTransactionState(state protocol.TransactionState) {
switch state {
case protocol.InTransaction, protocol.NotInTransaction:
// these states have no effect on session
break
case protocol.TransactionFailed, protocol.TransactionEnded:
if state == protocol.TransactionEnded {
for k, v := range s.pendingStmts {
s.stmts[k] = v
}
}
s.pendingStmts = map[string]*nodes.PrepareStmt{}
s.portals = map[string]*portal{}
}
}
func (s *session) prepare(parseMsg *pgproto3.Parse) (res []protocol.Message, err error) {
var tree parser.ParsetreeList
tree, err = parser.Parse(parseMsg.Query)
if err != nil {
res = append(res, protocol.ErrorResponse(SyntaxError(err.Error())))
return
}
ps := nodes.PrepareStmt{
Query: tree.Statements[0],
Argtypes: nodes.List{Items: make([]nodes.Node, len(parseMsg.ParameterOIDs))},
}
for i, p := range parseMsg.ParameterOIDs {
dt, ok := s.ConnInfo.DataTypeForOID(pgtype.OID(p))
if !ok {
res = append(res, protocol.ErrorResponse(fmt.Errorf("cache lookup failed for type %d", p)))
return
}
ps.Argtypes.Items[i] = nodes.TypeName{
TypeOid: nodes.Oid(p),
Names: nodes.List{
Items: []nodes.Node{
nodes.String{Str: dt.Name},
},
},
}
}
if parseMsg.Name == "" {
ps.Name = nil
} else {
ps.Name = &parseMsg.Name
}
s.storePreparedStatement(&ps)
res = append(res, protocol.ParseComplete)
return
}
func (s *session) storePreparedStatement(ps *nodes.PrepareStmt) {
name := ""
if ps.Name != nil {
name = *ps.Name
}
s.pendingStmts[name] = ps
}
func (s *session) describe(describeMsg *pgproto3.Describe) (res []protocol.Message, err error) {
switch describeMsg.ObjectType {
case protocol.DescribeStatement:
if ps, ok := s.stmts[describeMsg.Name]; !ok {
res = append(res, protocol.ErrorResponse(InvalidSQLStatementName(describeMsg.Name)))
} else {
var msg protocol.Message
msg, err = protocol.ParameterDescription(ps)
if err != nil {
return
}
res = append(res, msg)
// TODO: add a RowDescription message. this will require access to the backend
}
case protocol.DescribePortal:
err = Unsupported("object type '%c'", describeMsg.ObjectType)
default:
err = ProtocolViolation(fmt.Sprintf("invalid DESCRIBE message subtype '%c'", describeMsg.ObjectType))
}
return
}
func (s *session) bind(bindMsg *pgproto3.Bind) (res []protocol.Message, err error) {
_, exist := s.stmts[bindMsg.PreparedStatement]
if !exist {
res = append(res, protocol.ErrorResponse(InvalidSQLStatementName(bindMsg.PreparedStatement)))
return
}
s.portals[bindMsg.DestinationPortal] = &portal{
srcPreparedStatement: bindMsg.PreparedStatement,
parameters: bindMsg.Parameters,
}
res = append(res, protocol.BindComplete)
return
}
func (s *session) Set(k string, v interface{}) { s.Args[k] = v }
func (s *session) Get(k string) interface{} { return s.Args[k] }
func (s *session) Del(k string) { delete(s.Args, k) }
func (s *session) All() map[string]interface{} { return s.Args }