Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not swallow errors in simple query. Fixing transaction descriptors. Read envchanges correctly. #105

Merged
merged 3 commits into from
Dec 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ impl<S: AsyncRead + AsyncWrite + Unpin + Send> Client<S> {
{
self.connection.flush_stream().await?;

let req = BatchRequest::new(query, self.connection.context().transaction_id());
let req = BatchRequest::new(query, self.connection.context().transaction_descriptor());

let id = self.connection.context_mut().next_packet_id();
self.connection.send(PacketHeader::batch(id), req).await?;
Expand Down Expand Up @@ -278,7 +278,7 @@ impl<S: AsyncRead + AsyncWrite + Unpin + Send> Client<S> {
let req = TokenRpcRequest::new(
proc_id,
rpc_params,
self.connection.context().transaction_id(),
self.connection.context().transaction_descriptor(),
);

let id = self.connection.context_mut().next_packet_id();
Expand Down
8 changes: 4 additions & 4 deletions src/tds/codec/batch_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ use std::borrow::Cow;

pub struct BatchRequest<'a> {
queries: Cow<'a, str>,
transaction_id: u64,
transaction_descriptor: [u8; 8],
}

impl<'a> BatchRequest<'a> {
pub fn new(queries: impl Into<Cow<'a, str>>, transaction_id: u64) -> Self {
pub fn new(queries: impl Into<Cow<'a, str>>, transaction_descriptor: [u8; 8]) -> Self {
Self {
queries: queries.into(),
transaction_id,
transaction_descriptor,
}
}
}
Expand All @@ -21,7 +21,7 @@ impl<'a> Encode<BytesMut> for BatchRequest<'a> {
dst.put_u32_le(ALL_HEADERS_LEN_TX as u32);
dst.put_u32_le(ALL_HEADERS_LEN_TX as u32 - 4);
dst.put_u16_le(AllHeaderTy::TransactionDescriptor as u16);
dst.put_u64_le(self.transaction_id);
dst.put_slice(&self.transaction_descriptor);
dst.put_u32_le(1);

for c in self.queries.encode_utf16() {
Expand Down
8 changes: 4 additions & 4 deletions src/tds/codec/rpc_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,19 @@ pub struct TokenRpcRequest<'a> {
proc_id: RpcProcIdValue<'a>,
flags: RpcOptionFlags,
params: Vec<RpcParam<'a>>,
transaction_id: u64,
transaction_desc: [u8; 8],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is that change motivated by endianness concerns? I can see we write that with put_slice() instead of put_u64_le() now.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just do whatever the JDBC driver does. We always just write bytes to the message header, so there is no reason to convert that to an arbitrary number.

}

impl<'a> TokenRpcRequest<'a> {
pub fn new<I>(proc_id: I, params: Vec<RpcParam<'a>>, transaction_id: u64) -> Self
pub fn new<I>(proc_id: I, params: Vec<RpcParam<'a>>, transaction_desc: [u8; 8]) -> Self
where
I: Into<RpcProcIdValue<'a>>,
{
Self {
proc_id: proc_id.into(),
flags: RpcOptionFlags::empty(),
params,
transaction_id,
transaction_desc,
}
}
}
Expand Down Expand Up @@ -95,7 +95,7 @@ impl<'a> Encode<BytesMut> for TokenRpcRequest<'a> {
dst.put_u32_le(ALL_HEADERS_LEN_TX as u32);
dst.put_u32_le(ALL_HEADERS_LEN_TX as u32 - 4);
dst.put_u16_le(AllHeaderTy::TransactionDescriptor as u16);
dst.put_u64_le(self.transaction_id);
dst.put_slice(&self.transaction_desc);
dst.put_u32_le(1);

match self.proc_id {
Expand Down
134 changes: 86 additions & 48 deletions src/tds/codec/token/token_env_change.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
use crate::{
tds::{codec::read_varchar, lcid_to_encoding, sortid_to_encoding},
tds::{lcid_to_encoding, sortid_to_encoding},
Error, SqlReadBytes,
};
use byteorder::{LittleEndian, ReadBytesExt};
use encoding::Encoding;
use fmt::Debug;
use futures::io::AsyncReadExt;
use std::io::Cursor;
use std::io::Read;
use std::{convert::TryFrom, fmt};

uint_enum! {
Expand Down Expand Up @@ -107,10 +110,10 @@ pub enum TokenEnvChange {
old: CollationInfo,
new: CollationInfo,
},
BeginTransaction(u64),
CommitTransaction(u64),
RollbackTransaction(u64),
DefectTransaction(u64),
BeginTransaction([u8; 8]),
CommitTransaction,
RollbackTransaction,
DefectTransaction,
Routing {
host: String,
port: u16,
Expand All @@ -132,9 +135,9 @@ impl fmt::Display for TokenEnvChange {
write!(f, "SQL collation change from {} to {}", old, new)
}
Self::BeginTransaction(_) => write!(f, "Begin transaction"),
Self::CommitTransaction(_) => write!(f, "Commit transaction"),
Self::RollbackTransaction(_) => write!(f, "Rollback transaction"),
Self::DefectTransaction(_) => write!(f, "Defect transaction"),
Self::CommitTransaction => write!(f, "Commit transaction"),
Self::RollbackTransaction => write!(f, "Rollback transaction"),
Self::DefectTransaction => write!(f, "Defect transaction"),
Self::Routing { host, port } => write!(
f,
"Server requested routing to a new address: {}:{}",
Expand All @@ -151,82 +154,117 @@ impl TokenEnvChange {
where
R: SqlReadBytes + Unpin,
{
let _len = src.read_u16_le().await?;
let ty_byte = src.read_u8().await?;
let len = src.read_u16_le().await? as usize;

// We read all the bytes now, due to whatever environment change tokens
// we read, they might contain padding zeroes in the end we must
// discard.
let mut bytes = vec![0; len];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is one place where read-buf will come in handy — free performance improvement when it's stable.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, except we don't luckily read env tokens that often, and they're all quite short.

Still excited about that RFC.

src.read_exact(&mut bytes[0..len]).await?;

let mut buf = Cursor::new(bytes);
let ty_byte = buf.read_u8()?;

let ty = EnvChangeTy::try_from(ty_byte)
.map_err(|_| Error::Protocol(format!("invalid envchange type {:x}", ty_byte).into()))?;

let token = match ty {
EnvChangeTy::Database => {
let len = src.read_u8().await?;
let new_value = read_varchar(src, len).await?;
let len = buf.read_u8()? as usize;
let mut bytes = vec![0; len];

for i in 0..len {
bytes[i] = buf.read_u16::<LittleEndian>()?;
}

let len = src.read_u8().await?;
let old_value = read_varchar(src, len).await?;
let new_value = String::from_utf16(&bytes[..])?;

let len = buf.read_u8()? as usize;
let mut bytes = vec![0; len];

for i in 0..len {
bytes[i] = buf.read_u16::<LittleEndian>()?;
}

let old_value = String::from_utf16(&bytes[..])?;

TokenEnvChange::Database(new_value, old_value)
}
EnvChangeTy::PacketSize => {
let len = src.read_u8().await?;
let new_value = read_varchar(src, len).await?;
let len = buf.read_u8()? as usize;
let mut bytes = vec![0; len];

for i in 0..len {
bytes[i] = buf.read_u16::<LittleEndian>()?;
}

let new_value = String::from_utf16(&bytes[..])?;

let len = buf.read_u8()? as usize;
let mut bytes = vec![0; len];

for i in 0..len {
bytes[i] = buf.read_u16::<LittleEndian>()?;
}

let len = src.read_u8().await?;
let old_value = read_varchar(src, len).await?;
let old_value = String::from_utf16(&bytes[..])?;

TokenEnvChange::PacketSize(new_value.parse()?, old_value.parse()?)
}
EnvChangeTy::SqlCollation => {
let len = src.read_u8().await? as usize;
let len = buf.read_u8()? as usize;
let mut new_value = vec![0; len];
src.read_exact(&mut new_value[0..len]).await?;
buf.read_exact(&mut new_value[0..len])?;

let len = src.read_u8().await? as usize;
let len = buf.read_u8()? as usize;
let mut old_value = vec![0; len];
src.read_exact(&mut old_value[0..len]).await?;
buf.read_exact(&mut old_value[0..len])?;

TokenEnvChange::SqlCollation {
new: CollationInfo::new(new_value.as_slice()),
old: CollationInfo::new(old_value.as_slice()),
}
}
EnvChangeTy::BeginTransaction | EnvChangeTy::EnlistDTCTransaction => {
src.read_u8().await?;
let desc = src.read_u64_le().await?;
let len = buf.read_u8()?;
assert!(len == 8);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know if this is really needed. The JDBC code is extremely careful asserting all the things. The TDS standard dictates how the descriptor is always 8 bytes. And the only implementation is the SQL Server from Microsoft, which I highly doubt would send 9 bytes descriptor every now and then...


let mut desc = [0; 8];
buf.read_exact(&mut desc)?;

TokenEnvChange::BeginTransaction(desc)
}
EnvChangeTy::CommitTransaction => {
src.read_u8().await?;
let desc = src.read_u64_le().await?;
TokenEnvChange::CommitTransaction(desc)
}
EnvChangeTy::RollbackTransaction => {
src.read_u8().await?;
let desc = src.read_u64_le().await?;
TokenEnvChange::RollbackTransaction(desc)
}
EnvChangeTy::DefectTransaction => {
src.read_u8().await?;
let desc = src.read_u64_le().await?;
TokenEnvChange::DefectTransaction(desc)
}

EnvChangeTy::CommitTransaction => TokenEnvChange::CommitTransaction,
EnvChangeTy::RollbackTransaction => TokenEnvChange::RollbackTransaction,
EnvChangeTy::DefectTransaction => TokenEnvChange::DefectTransaction,

EnvChangeTy::Routing => {
src.read_u16_le().await?; // routing data value length
src.read_u8().await?; // routing protocol, always 0 (tcp)
buf.read_u16::<LittleEndian>()?; // routing data value length
buf.read_u8()?; // routing protocol, always 0 (tcp)

let port = buf.read_u16::<LittleEndian>()?;

let port = src.read_u16_le().await?;
let len = buf.read_u16::<LittleEndian>()? as usize; // hostname string length
let mut bytes = vec![0; len];

let len = src.read_u16_le().await?; // hostname string length
let host = read_varchar(src, len).await?;
for i in 0..len {
bytes[i] = buf.read_u16::<LittleEndian>()?;
}

// ??? but needed...
src.read_u16_le().await?;
let host = String::from_utf16(&bytes[..])?;

TokenEnvChange::Routing { host, port }
}
EnvChangeTy::RTLS => {
let len = src.read_u8().await?;
let mirror_name = read_varchar(src, len).await?;
let len = buf.read_u8()? as usize;
let mut bytes = vec![0; len];

for i in 0..len {
bytes[i] = buf.read_u16::<LittleEndian>()?;
}

let mirror_name = String::from_utf16(&bytes[..])?;

TokenEnvChange::ChangeMirror(mirror_name)
}
Expand Down
12 changes: 6 additions & 6 deletions src/tds/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub(crate) struct Context {
version: FeatureLevel,
packet_size: u32,
packet_id: u8,
transaction_id: u64,
transaction_desc: [u8; 8],
last_meta: Option<Arc<TokenColMetaData>>,
spn: Option<String>,
}
Expand All @@ -18,7 +18,7 @@ impl Context {
version: FeatureLevel::SqlServerN,
packet_size: 4096,
packet_id: 0,
transaction_id: 0,
transaction_desc: [0; 8],
last_meta: None,
spn: None,
}
Expand Down Expand Up @@ -46,12 +46,12 @@ impl Context {
self.packet_size = new_size;
}

pub fn transaction_id(&self) -> u64 {
self.transaction_id
pub fn transaction_descriptor(&self) -> [u8; 8] {
self.transaction_desc
}

pub fn set_transaction_id(&mut self, id: u64) {
self.transaction_id = id;
pub fn set_transaction_descriptor(&mut self, desc: [u8; 8]) {
self.transaction_desc = desc;
}

pub fn version(&self) -> FeatureLevel {
Expand Down
11 changes: 5 additions & 6 deletions src/tds/stream/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,16 @@ impl<'a> QueryStream<'a> {

return Ok(());
}
Some(ReceivedToken::DoneInProc(_)) | Some(ReceivedToken::DoneProc(_)) => {
return Ok(());
}
Some(ReceivedToken::Done(done)) if done.has_more() => return Ok(()),
_ => {
if self.columns().is_none() {
Some(ReceivedToken::DoneInProc(done))
| Some(ReceivedToken::DoneProc(done))
| Some(ReceivedToken::Done(done)) => {
if !done.has_more() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So if I understand this correctly, this is the part about swallowed errors?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah. We must go through the whole stream always. We might get any of the done tokens, but they have a bitflag set if there's more data to be come.

self.state = QueryStreamState::Done;
}

return Ok(());
}
_ => return Ok(()),
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/tds/stream/token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,12 +144,12 @@ where
self.conn.context_mut().set_packet_size(new_size);
}
TokenEnvChange::BeginTransaction(desc) => {
self.conn.context_mut().set_transaction_id(desc);
self.conn.context_mut().set_transaction_descriptor(desc);
}
TokenEnvChange::CommitTransaction(_)
| TokenEnvChange::RollbackTransaction(_)
| TokenEnvChange::DefectTransaction(_) => {
self.conn.context_mut().set_transaction_id(0);
TokenEnvChange::CommitTransaction
| TokenEnvChange::RollbackTransaction
| TokenEnvChange::DefectTransaction => {
self.conn.context_mut().set_transaction_descriptor([0; 8]);
}
_ => (),
}
Expand Down