Skip to content

RUST-725 Use "hello" for handshake and heartbeat when an API version is declared #380

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

Merged
merged 4 commits into from
Jun 30, 2021
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
58 changes: 8 additions & 50 deletions src/cmap/establish/handshake/mod.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
#[cfg(test)]
mod test;

use std::time::Instant;

use lazy_static::lazy_static;
use os_info::{Type, Version};

use crate::{
bson::{doc, Bson, Document},
client::auth::{ClientFirst, FirstRound},
cmap::{options::ConnectionPoolOptions, Command, Connection, StreamDescription},
error::{ErrorKind, Result},
is_master::{IsMasterCommandResponse, IsMasterReply},
error::Result,
is_master::{is_master_command, run_is_master, IsMasterReply},
options::{AuthMechanism, ClientOptions, Credential, DriverInfo, ServerApi},
};

Expand Down Expand Up @@ -148,12 +146,9 @@ impl Handshaker {
pub(crate) fn new(options: Option<HandshakerOptions>) -> Self {
let mut metadata = BASE_CLIENT_METADATA.clone();
let mut credential = None;
let mut db = None;
let mut server_api = None;

let mut body = doc! {
"isMaster": 1,
};
let mut command =
is_master_command(options.as_ref().and_then(|opts| opts.server_api.as_ref()));

if let Some(options) = options {
if let Some(app_name) = options.app_name {
Expand All @@ -178,25 +173,13 @@ impl Handshaker {
}

if let Some(cred) = options.credential {
cred.append_needed_mechanism_negotiation(&mut body);
db = Some(cred.resolved_source().to_string());
cred.append_needed_mechanism_negotiation(&mut command.body);
command.target_db = cred.resolved_source().to_string();
credential = Some(cred);
}

server_api = options.server_api;
}

body.insert("client", metadata);

let mut command = Command::new(
"isMaster".to_string(),
db.unwrap_or_else(|| "admin".to_string()),
body,
);

if let Some(server_api) = server_api {
command.set_server_api(&server_api)
}
command.body.insert("client", metadata);

Self {
command,
Expand All @@ -210,7 +193,7 @@ impl Handshaker {

let client_first = set_speculative_auth_info(&mut command.body, self.credential.as_ref())?;

let mut is_master_reply = is_master(command, conn).await?;
let mut is_master_reply = run_is_master(command, conn).await?;
conn.stream_description = Some(StreamDescription::from_is_master(is_master_reply.clone()));

// Record the client's message and the server's response from speculative authentication if
Expand Down Expand Up @@ -273,31 +256,6 @@ impl From<ClientOptions> for HandshakerOptions {
}
}

/// Run the given isMaster command.
///
/// If the given command is not an isMaster, this function will return an error.
pub(crate) async fn is_master(command: Command, conn: &mut Connection) -> Result<IsMasterReply> {
if !command.name.eq_ignore_ascii_case("ismaster") {
return Err(ErrorKind::Internal {
message: format!("invalid ismaster command: {}", command.name),
}
.into());
}
let start_time = Instant::now();
let response = conn.send_command(command, None).await?;
let end_time = Instant::now();

response.validate()?;
let cluster_time = response.cluster_time().cloned();
let command_response: IsMasterCommandResponse = response.body()?;

Ok(IsMasterReply {
command_response,
round_trip_time: Some(end_time.duration_since(start_time)),
cluster_time,
})
}

/// Updates the handshake command document with the speculative authenitication info.
fn set_speculative_auth_info(
command: &mut Document,
Expand Down
2 changes: 1 addition & 1 deletion src/cmap/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use derivative::Derivative;
pub use self::conn::ConnectionInfo;
pub(crate) use self::{
conn::{Command, CommandResponse, Connection, StreamDescription},
establish::handshake::{is_master, Handshaker},
establish::handshake::Handshaker,
status::PoolGenerationSubscriber,
};
use self::{connection_requester::ConnectionRequestResult, options::ConnectionPoolOptions};
Expand Down
50 changes: 47 additions & 3 deletions src/is_master.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,55 @@
use std::time::Duration;
use std::time::{Duration, Instant};

use serde::Deserialize;

use crate::{
bson::{oid::ObjectId, DateTime, Document, Timestamp},
client::ClusterTime,
bson::{doc, oid::ObjectId, DateTime, Document, Timestamp},
client::{options::ServerApi, ClusterTime},
cmap::{Command, Connection},
error::{ErrorKind, Result},
sdam::ServerType,
selection_criteria::TagSet,
};

/// Construct an isMaster command.
pub(crate) fn is_master_command(api: Option<&ServerApi>) -> Command {
let command_name = if api.is_some() { "hello" } else { "isMaster" };
let mut command = Command::new(command_name.into(), "admin".into(), doc! { command_name: 1 });
if let Some(server_api) = api {
command.set_server_api(server_api);
}
command
}

/// Run the given isMaster command.
///
/// If the given command is not an isMaster, this function will return an error.
pub(crate) async fn run_is_master(
command: Command,
conn: &mut Connection,
) -> Result<IsMasterReply> {
if !command.name.eq_ignore_ascii_case("ismaster") &&
!command.name.eq_ignore_ascii_case("hello") {
return Err(ErrorKind::Internal {
message: format!("invalid ismaster command: {}", command.name),
}
.into());
}
let start_time = Instant::now();
let response = conn.send_command(command, None).await?;
let end_time = Instant::now();

response.validate()?;
let cluster_time = response.cluster_time().cloned();
let command_response: IsMasterCommandResponse = response.body()?;

Ok(IsMasterReply {
command_response,
round_trip_time: Some(end_time.duration_since(start_time)),
cluster_time,
})
}

#[derive(Debug, Clone)]
pub(crate) struct IsMasterReply {
pub command_response: IsMasterCommandResponse,
Expand All @@ -19,6 +60,7 @@ pub(crate) struct IsMasterReply {
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct IsMasterCommandResponse {
pub is_writable_primary: Option<bool>,
#[serde(rename = "ismaster")]
pub is_master: Option<bool>,
pub ok: Option<f32>,
Expand Down Expand Up @@ -72,6 +114,8 @@ impl IsMasterCommandResponse {
} else if self.set_name.is_some() {
if let Some(true) = self.hidden {
ServerType::RsOther
} else if let Some(true) = self.is_writable_primary {
ServerType::RsPrimary
} else if let Some(true) = self.is_master {
ServerType::RsPrimary
} else if let Some(true) = self.secondary {
Expand Down
2 changes: 1 addition & 1 deletion src/sdam/description/topology/server_selection/test/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ fn is_master_response_from_server_type(server_type: ServerType) -> IsMasterComma
ServerType::RsPrimary => {
response.ok = Some(1.0);
response.set_name = Some("foo".into());
response.is_master = Some(true);
response.is_writable_primary = Some(true);
}
ServerType::RsOther => {
response.ok = Some(1.0);
Expand Down
13 changes: 4 additions & 9 deletions src/sdam/monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@ use super::{
ServerUpdateReceiver,
};
use crate::{
bson::doc,
cmap::{is_master, Command, Connection, Handshaker},
cmap::{Connection, Handshaker},
error::{Error, Result},
is_master::IsMasterReply,
is_master::{is_master_command, run_is_master, IsMasterReply},
options::{ClientOptions, ServerAddress},
RUNTIME,
};
Expand Down Expand Up @@ -184,12 +183,8 @@ impl HeartbeatMonitor {
async fn perform_is_master(&mut self) -> Result<IsMasterReply> {
let result = match self.connection {
Some(ref mut conn) => {
let mut command =
Command::new("isMaster".into(), "admin".into(), doc! { "isMaster": 1 });
if let Some(ref server_api) = self.client_options.server_api {
command.set_server_api(server_api);
}
is_master(command, conn).await
let command = is_master_command(self.client_options.server_api.as_ref());
run_is_master(command, conn).await
}
None => {
let mut connection = Connection::connect_monitoring(
Expand Down
2 changes: 1 addition & 1 deletion src/test/spec/versioned_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use super::run_unified_format_test;
#[cfg_attr(feature = "async-std-runtime", async_std::test)]
async fn run() {
let _guard: RwLockWriteGuard<_> = LOCK.run_exclusively().await;
// TODO RUST-725 Unskip these tests on 5.0
// TODO RUST-768 Unskip these tests on 5.0
if TestClient::new().await.server_version_gte(5, 0) {
return;
}
Expand Down