Skip to content

Commit dce72ba

Browse files
authored
Add debug logging (#39)
* Add debug for easier debugging * fmt * a couple more messages
1 parent af1716b commit dce72ba

File tree

3 files changed

+61
-5
lines changed

3 files changed

+61
-5
lines changed

src/client.rs

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
/// We are pretending to the server in this scenario,
33
/// and this module implements that.
44
use bytes::{Buf, BufMut, BytesMut};
5-
use log::error;
5+
use log::{debug, error};
66
use tokio::io::{AsyncReadExt, BufReader};
77
use tokio::net::{
88
tcp::{OwnedReadHalf, OwnedWriteHalf},
@@ -70,6 +70,8 @@ impl Client {
7070
let transaction_mode = config.general.pool_mode.starts_with("t");
7171
drop(config);
7272
loop {
73+
debug!("Waiting for StartupMessage");
74+
7375
// Could be StartupMessage or SSLRequest
7476
// which makes this variable length.
7577
let len = match stream.read_i32().await {
@@ -91,6 +93,8 @@ impl Client {
9193
match code {
9294
// Client wants SSL. We don't support it at the moment.
9395
SSL_REQUEST_CODE => {
96+
debug!("Rejecting SSLRequest");
97+
9498
let mut no = BytesMut::with_capacity(1);
9599
no.put_u8(b'N');
96100

@@ -99,6 +103,8 @@ impl Client {
99103

100104
// Regular startup message.
101105
PROTOCOL_VERSION_NUMBER => {
106+
debug!("Got StartupMessage");
107+
102108
// TODO: perform actual auth.
103109
let parameters = parse_startup(bytes.clone())?;
104110

@@ -110,6 +116,7 @@ impl Client {
110116
write_all(&mut stream, server_info).await?;
111117
backend_key_data(&mut stream, process_id, secret_key).await?;
112118
ready_for_query(&mut stream).await?;
119+
debug!("Startup OK");
113120

114121
// Split the read and write streams
115122
// so we can control buffering.
@@ -161,6 +168,8 @@ impl Client {
161168
pub async fn handle(&mut self, mut pool: ConnectionPool) -> Result<(), Error> {
162169
// The client wants to cancel a query it has issued previously.
163170
if self.cancel_mode {
171+
debug!("Sending CancelRequest");
172+
164173
let (process_id, secret_key, address, port) = {
165174
let guard = self.client_server_map.lock().unwrap();
166175

@@ -193,6 +202,8 @@ impl Client {
193202
// We expect the client to either start a transaction with regular queries
194203
// or issue commands for our sharding and server selection protocols.
195204
loop {
205+
debug!("Client idle, waiting for message");
206+
196207
// Client idle, waiting for messages.
197208
self.stats.client_idle(self.process_id);
198209

@@ -203,6 +214,12 @@ impl Client {
203214
// SET SHARDING KEY TO 'bigint';
204215
let mut message = read_message(&mut self.read).await?;
205216

217+
// Avoid taking a server if the client just wants to disconnect.
218+
if message[0] as char == 'X' {
219+
debug!("Client disconnecting");
220+
return Ok(());
221+
}
222+
206223
// Handle all custom protocol commands here.
207224
match query_router.try_execute_command(message.clone()) {
208225
// Normal query
@@ -250,9 +267,14 @@ impl Client {
250267
// Waiting for server connection.
251268
self.stats.client_waiting(self.process_id);
252269

270+
debug!("Waiting for connection from pool");
271+
253272
// Grab a server from the pool: the client issued a regular query.
254273
let connection = match pool.get(query_router.shard(), query_router.role()).await {
255-
Ok(conn) => conn,
274+
Ok(conn) => {
275+
debug!("Got connection from pool");
276+
conn
277+
}
256278
Err(err) => {
257279
error!("Could not get connection from pool: {:?}", err);
258280
error_response(&mut self.write, "could not get connection from the pool")
@@ -272,11 +294,19 @@ impl Client {
272294
self.stats.client_active(self.process_id);
273295
self.stats.server_active(server.process_id());
274296

297+
debug!(
298+
"Client {:?} talking to server {:?}",
299+
self.write.peer_addr().unwrap(),
300+
server.address()
301+
);
302+
275303
// Transaction loop. Multiple queries can be issued by the client here.
276304
// The connection belongs to the client until the transaction is over,
277305
// or until the client disconnects if we are in session mode.
278306
loop {
279307
let mut message = if message.len() == 0 {
308+
debug!("Waiting for message inside transaction or in session mode");
309+
280310
match read_message(&mut self.read).await {
281311
Ok(message) => message,
282312
Err(err) => {
@@ -303,9 +333,13 @@ impl Client {
303333
let code = message.get_u8() as char;
304334
let _len = message.get_i32() as usize;
305335

336+
debug!("Message: {}", code);
337+
306338
match code {
307339
// ReadyForQuery
308340
'Q' => {
341+
debug!("Sending query to server");
342+
309343
// TODO: implement retries here for read-only transactions.
310344
server.send(original).await?;
311345

@@ -387,6 +421,8 @@ impl Client {
387421
// Sync
388422
// Frontend (client) is asking for the query result now.
389423
'S' => {
424+
debug!("Sending query to server");
425+
390426
self.buffer.put(&original[..]);
391427

392428
// TODO: retries for read-only transactions.
@@ -471,6 +507,7 @@ impl Client {
471507
}
472508

473509
// The server is no longer bound to us, we can't cancel it's queries anymore.
510+
debug!("Releasing server back into the pool");
474511
self.release();
475512
}
476513
}

src/query_router.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,12 @@ impl QueryRouter {
194194
let len = buf.get_i32() as usize;
195195

196196
let query = match code {
197-
'Q' => String::from_utf8_lossy(&buf[..len - 5]).to_string(),
197+
'Q' => {
198+
let query = String::from_utf8_lossy(&buf[..len - 5]).to_string();
199+
debug!("Query: '{}'", query);
200+
query
201+
}
202+
198203
'P' => {
199204
let mut start = 0;
200205
let mut end;
@@ -213,6 +218,8 @@ impl QueryRouter {
213218

214219
let query = String::from_utf8_lossy(&buf[start..end]).to_string();
215220

221+
debug!("Prepared statement: '{}'", query);
222+
216223
query.replace("$", "") // Remove placeholders turning them into "values"
217224
}
218225
_ => return false,
@@ -221,7 +228,7 @@ impl QueryRouter {
221228
let ast = match Parser::parse_sql(&PostgreSqlDialect {}, &query) {
222229
Ok(ast) => ast,
223230
Err(err) => {
224-
debug!("{:?}, query: {}", err, query);
231+
debug!("{}", err.to_string());
225232
return false;
226233
}
227234
};

src/server.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use bytes::{Buf, BufMut, BytesMut};
22
///! Implementation of the PostgreSQL server (database) protocol.
33
///! Here we are pretending to the a Postgres client.
4-
use log::{error, info};
4+
use log::{debug, error, info};
55
use tokio::io::{AsyncReadExt, BufReader};
66
use tokio::net::{
77
tcp::{OwnedReadHalf, OwnedWriteHalf},
@@ -75,6 +75,8 @@ impl Server {
7575
}
7676
};
7777

78+
debug!("Sending StartupMessage");
79+
7880
// Send the startup packet telling the server we're a normal Postgres client.
7981
startup(&mut stream, &user.name, database).await?;
8082

@@ -95,6 +97,8 @@ impl Server {
9597
Err(_) => return Err(Error::SocketError),
9698
};
9799

100+
debug!("Message: {}", code);
101+
98102
match code {
99103
// Authentication
100104
'R' => {
@@ -104,6 +108,8 @@ impl Server {
104108
Err(_) => return Err(Error::SocketError),
105109
};
106110

111+
debug!("Auth: {}", auth_code);
112+
107113
match auth_code {
108114
MD5_ENCRYPTED_PASSWORD => {
109115
// The salt is 4 bytes.
@@ -135,6 +141,8 @@ impl Server {
135141
Err(_) => return Err(Error::SocketError),
136142
};
137143

144+
debug!("Error: {}", error_code);
145+
138146
match error_code {
139147
// No error message is present in the message.
140148
MESSAGE_TERMINATOR => (),
@@ -247,6 +255,8 @@ impl Server {
247255
}
248256
};
249257

258+
debug!("Sending CancelRequest");
259+
250260
let mut bytes = BytesMut::with_capacity(16);
251261
bytes.put_i32(16);
252262
bytes.put_i32(CANCEL_REQUEST_CODE);
@@ -290,6 +300,8 @@ impl Server {
290300
let code = message.get_u8() as char;
291301
let _len = message.get_i32();
292302

303+
debug!("Message: {}", code);
304+
293305
match code {
294306
// ReadyForQuery
295307
'Z' => {

0 commit comments

Comments
 (0)