Skip to content

Commit 48a2d84

Browse files
committed
Allow cloning the transport with different credentials
1 parent 1d64abd commit 48a2d84

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

elasticsearch/src/http/transport.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -711,6 +711,20 @@ impl Transport {
711711
pub fn set_auth(&self, credentials: Credentials) {
712712
*self.credentials.write() = Some(credentials);
713713
}
714+
715+
/// Creates a new `Transport` that is a clone of this one, except for authentication
716+
/// credentials. This is the opposite of [`Transport::set_auth()`]. Typically used
717+
/// when working in multi-tenant environments where credentials can vary with every
718+
/// request.
719+
pub fn clone_with_auth(&self, credentials: Option<Credentials>) -> Self {
720+
Self {
721+
client: self.client.clone(),
722+
credentials: Arc::new(RwLock::new(credentials)),
723+
conn_pool: self.conn_pool.clone(),
724+
request_body_compression: self.request_body_compression,
725+
send_meta: self.send_meta,
726+
}
727+
}
714728
}
715729

716730
impl Default for Transport {
@@ -1298,4 +1312,28 @@ pub mod tests {
12981312

12991313
Ok(())
13001314
}
1315+
1316+
#[test]
1317+
fn clone_with_credentials() -> anyhow::Result<()> {
1318+
let t1: Transport = TransportBuilder::new(SingleNodeConnectionPool::default())
1319+
.auth(Credentials::Basic("foo".to_string(), "bar".to_string()))
1320+
.build()?;
1321+
1322+
let t2 = t1.clone_with_auth(Some(Credentials::Bearer("The bear".to_string())));
1323+
1324+
if let Some(Credentials::Basic(login, password)) = t1.credentials.read().as_ref() {
1325+
assert_eq!(login, "foo");
1326+
assert_eq!(password, "bar");
1327+
} else {
1328+
panic!("Expected Basic credentials");
1329+
}
1330+
1331+
if let Some(Credentials::Bearer(token)) = t2.credentials.read().as_ref() {
1332+
assert_eq!(token, "The bear");
1333+
} else {
1334+
panic!("Expected Bearer credentials");
1335+
}
1336+
1337+
Ok(())
1338+
}
13011339
}

0 commit comments

Comments
 (0)