-
Notifications
You must be signed in to change notification settings - Fork 0
/
replaying_hub.go
248 lines (217 loc) · 6.46 KB
/
replaying_hub.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
package pgvcr
import (
"braces.dev/errtrace"
"context"
"errors"
"github.com/jackc/pgx/v5/pgproto3"
"golang.org/x/sync/errgroup"
"io"
"log/slog"
"net"
"slices"
"sync"
"time"
)
type incomingMessage struct {
connectionID uint64
message pgproto3.Message
}
type replayingConnection struct {
connectionID uint64
conn net.Conn
pgprotoBackend *pgproto3.Backend
}
type replayingHub struct {
listener net.Listener
replayer *replayer
connections []replayingConnection
incomingMessagesChan chan incomingMessage
connectionIDsMap map[uint64]uint64
lock sync.Mutex
}
func (h *replayingHub) addConnection(connID uint64, backend *pgproto3.Backend) {
h.lock.Lock()
defer h.lock.Unlock()
h.connections = append(h.connections, replayingConnection{
connectionID: connID,
pgprotoBackend: backend,
})
}
func startReplayHub(ctx context.Context, r *replayer, listener net.Listener) error {
ctx, cancelFn := context.WithCancel(ctx)
defer cancelFn()
h := &replayingHub{
listener: listener,
replayer: r,
connections: make([]replayingConnection, 0, 1),
incomingMessagesChan: make(chan incomingMessage),
connectionIDsMap: make(map[uint64]uint64),
lock: sync.Mutex{},
}
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
return errtrace.Wrap(h.acceptConnectionsLoop(ctx))
})
eg.Go(func() error {
return errtrace.Wrap(h.mainLoop(ctx))
})
return errtrace.Wrap(eg.Wait())
}
func (h *replayingHub) acceptConnectionsLoop(ctx context.Context) error {
connectionID := uint64(0)
for ctx.Err() == nil {
conn, err := h.listener.Accept()
if errors.Is(err, net.ErrClosed) {
return nil
}
if err != nil {
return errtrace.Wrap(err)
}
_ = context.AfterFunc(ctx, func() {
_ = conn.Close()
})
rConn := replayingConnection{
connectionID: connectionID,
conn: conn,
pgprotoBackend: pgproto3.NewBackend(conn, conn),
}
h.lock.Lock()
h.connections = append(h.connections, rConn)
h.lock.Unlock()
go h.receiveMessagesLoop(ctx, rConn)
connectionID++
}
return errtrace.Wrap(ctx.Err())
}
func (h *replayingHub) receiveMessagesLoop(ctx context.Context, conn replayingConnection) {
err := h.handleStartup(ctx, conn)
if err != nil {
logError(ctx, errtrace.Errorf("handling connection startup: %w", err))
// TODO: close connection? send error on wire?
return
}
for ctx.Err() == nil {
msg, err := conn.pgprotoBackend.Receive()
if errors.Is(err, net.ErrClosed) || (err != nil && err.Error() == io.EOF.Error()) {
return
}
if err != nil {
logError(ctx, errtrace.Errorf("receiving message: %w", err))
// TODO: close connection? send error on wire?
return
}
if isPingQuery(msg) {
logDebug(ctx, "sending ping response") // FIXME
conn.pgprotoBackend.Send(&pgproto3.EmptyQueryResponse{})
conn.pgprotoBackend.Send(&pgproto3.ReadyForQuery{TxStatus: 'I'})
err := conn.pgprotoBackend.Flush()
if err != nil {
logError(ctx, errtrace.Errorf("sending ping response: %w", err))
// TODO: close connection? send error on wire?
return
}
continue
}
h.incomingMessagesChan <- incomingMessage{
connectionID: conn.connectionID,
message: msg,
}
}
}
func (h *replayingHub) handleStartup(ctx context.Context, conn replayingConnection) error {
logDebug(ctx, "expecting startup message")
startupMessage, err := conn.pgprotoBackend.ReceiveStartupMessage()
if err != nil {
return errtrace.Errorf("error receiving startup message: %w", err)
}
logDebug(ctx, "received startup message", slog.Any("startupMessage", startupMessage))
switch startupMessage.(type) {
case *pgproto3.StartupMessage:
buf, err := (&pgproto3.AuthenticationOk{}).Encode(nil)
if err != nil {
return errtrace.Wrap(err)
}
logDebug(ctx, "sending AuthenticationOk")
_, err = conn.conn.Write(buf)
if err != nil {
return errtrace.Wrap(err)
}
err = h.replayer.ConsumeGreetings(func(msgs []messageWithID) error {
for _, msg := range msgs {
conn.pgprotoBackend.Send(msg.Message.(pgproto3.BackendMessage))
}
return errtrace.Wrap(conn.pgprotoBackend.Flush())
})
if err != nil {
return errtrace.Wrap(err)
}
case *pgproto3.SSLRequest:
logDebug(ctx, "refusing SSL")
_, err = conn.conn.Write([]byte("N"))
if err != nil {
return errtrace.Wrap(err)
}
return errtrace.Wrap(h.handleStartup(ctx, conn))
default:
return errtrace.Errorf("unknown startup message: %#v", startupMessage)
}
return nil
}
func (h *replayingHub) mainLoop(ctx context.Context) error {
for ctx.Err() == nil {
err := h.replayer.ConsumeNext(func(expectedMessage messageWithID) error {
if expectedMessage.IsIncoming {
return errtrace.Wrap(h.processIncomingMessage(ctx, expectedMessage))
}
return errtrace.Wrap(h.processOutgoingMessage(expectedMessage))
})
if errors.Is(err, errNoMoreMessages) {
return nil
}
if err != nil {
return errtrace.Wrap(err)
}
}
return errtrace.Wrap(ctx.Err())
}
func (h *replayingHub) processOutgoingMessage(expectedMessage messageWithID) error {
h.lock.Lock()
pgprotoBackend := h.connections[len(h.connections)-1].pgprotoBackend
connectionID, ok := h.connectionIDsMap[expectedMessage.ConnectionID]
if ok {
connectionIndex := slices.IndexFunc(h.connections, func(connection replayingConnection) bool {
return connection.connectionID == connectionID
})
if connectionIndex != -1 {
pgprotoBackend = h.connections[connectionIndex].pgprotoBackend
}
}
h.lock.Unlock()
pgprotoBackend.Send(expectedMessage.Message.(pgproto3.BackendMessage))
return errtrace.Wrap(pgprotoBackend.Flush())
}
func (h *replayingHub) processIncomingMessage(ctx context.Context, expectedMessage messageWithID) error {
var actualMessage incomingMessage
select {
case <-time.After(time.Minute):
return errtrace.Errorf("timed out waiting for incoming message")
case actualMessage = <-h.incomingMessagesChan:
}
h.lock.Lock()
h.connectionIDsMap[expectedMessage.ConnectionID] = actualMessage.connectionID
h.lock.Unlock()
var expectedBytes, actualBytes []byte
var err error
expectedBytes, err = expectedMessage.Message.Encode(expectedBytes)
if err != nil {
return errtrace.Wrap(err)
}
actualBytes, err = actualMessage.message.Encode(actualBytes)
if err != nil {
return errtrace.Wrap(err)
}
if !slices.Equal(expectedBytes, actualBytes) {
return errtrace.Errorf("unexpected message \nexpected(%#v) \n!= \nactual(%#v)", expectedMessage.Message, actualMessage.message)
}
return nil
}