Struct scylla::transport::session_builder::GenericSessionBuilder
source · pub struct GenericSessionBuilder<Kind: SessionBuilderKind> {
pub config: SessionConfig,
/* private fields */
}
Expand description
SessionBuilder is used to create new Session instances
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.compression(Some(Compression::Snappy))
.build()
.await?;
Fields§
§config: SessionConfig
Implementations§
source§impl GenericSessionBuilder<DefaultMode>
impl GenericSessionBuilder<DefaultMode>
sourcepub fn known_node(self, hostname: impl AsRef<str>) -> Self
pub fn known_node(self, hostname: impl AsRef<str>) -> Self
Add a known node with a hostname
§Examples
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.build()
.await?;
let session: Session = SessionBuilder::new()
.known_node("db1.example.com")
.build()
.await?;
sourcepub fn known_node_addr(self, node_addr: SocketAddr) -> Self
pub fn known_node_addr(self, node_addr: SocketAddr) -> Self
Add a known node with an IP address
§Example
let session: Session = SessionBuilder::new()
.known_node_addr(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 9042))
.build()
.await?;
sourcepub fn known_nodes(
self,
hostnames: impl IntoIterator<Item = impl AsRef<str>>,
) -> Self
pub fn known_nodes( self, hostnames: impl IntoIterator<Item = impl AsRef<str>>, ) -> Self
Add a list of known nodes with hostnames
§Example
let session: Session = SessionBuilder::new()
.known_nodes(["127.0.0.1:9042", "db1.example.com"])
.build()
.await?;
sourcepub fn known_nodes_addr(
self,
node_addrs: impl IntoIterator<Item = impl Borrow<SocketAddr>>,
) -> Self
pub fn known_nodes_addr( self, node_addrs: impl IntoIterator<Item = impl Borrow<SocketAddr>>, ) -> Self
Add a list of known nodes with IP addresses
§Example
let addr1 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(172, 17, 0, 3)), 9042);
let addr2 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(172, 17, 0, 4)), 9042);
let session: Session = SessionBuilder::new()
.known_nodes_addr([addr1, addr2])
.build()
.await?;
sourcepub fn user(
self,
username: impl Into<String>,
passwd: impl Into<String>,
) -> Self
pub fn user( self, username: impl Into<String>, passwd: impl Into<String>, ) -> Self
Set username and password for plain text authentication.
If the database server will require authentication\
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.use_keyspace("my_keyspace_name", false)
.user("cassandra", "cassandra")
.build()
.await?;
sourcepub fn authenticator_provider(
self,
authenticator_provider: Arc<dyn AuthenticatorProvider>,
) -> Self
pub fn authenticator_provider( self, authenticator_provider: Arc<dyn AuthenticatorProvider>, ) -> Self
Set custom authenticator provider to create an authenticator instance during a session creation.
§Example
use bytes::Bytes;
use scylla::{Session, SessionBuilder};
use async_trait::async_trait;
use scylla::authentication::{AuthenticatorProvider, AuthenticatorSession, AuthError};
struct CustomAuthenticator;
#[async_trait]
impl AuthenticatorSession for CustomAuthenticator {
async fn evaluate_challenge(&mut self, token: Option<&[u8]>) -> Result<Option<Vec<u8>>, AuthError> {
Ok(None)
}
async fn success(&mut self, token: Option<&[u8]>) -> Result<(), AuthError> {
Ok(())
}
}
struct CustomAuthenticatorProvider;
#[async_trait]
impl AuthenticatorProvider for CustomAuthenticatorProvider {
async fn start_authentication_session(&self, _authenticator_name: &str) -> Result<(Option<Vec<u8>>, Box<dyn AuthenticatorSession>), AuthError> {
Ok((None, Box::new(CustomAuthenticator)))
}
}
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.use_keyspace("my_keyspace_name", false)
.user("cassandra", "cassandra")
.authenticator_provider(Arc::new(CustomAuthenticatorProvider))
.build()
.await?;
sourcepub fn address_translator(self, translator: Arc<dyn AddressTranslator>) -> Self
pub fn address_translator(self, translator: Arc<dyn AddressTranslator>) -> Self
Uses a custom address translator for peer addresses retrieved from the cluster. By default, no translation is performed.
§Example
struct IdentityTranslator;
#[async_trait]
impl AddressTranslator for IdentityTranslator {
async fn translate_address(
&self,
untranslated_peer: &UntranslatedPeer
) -> Result<SocketAddr, TranslationError> {
Ok(untranslated_peer.untranslated_address)
}
}
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.address_translator(Arc::new(IdentityTranslator))
.build()
.await?;
§Example
let mut translation_rules = HashMap::new();
let addr_before_translation = SocketAddr::from_str("192.168.0.42:19042").unwrap();
let addr_after_translation = SocketAddr::from_str("157.123.12.42:23203").unwrap();
translation_rules.insert(addr_before_translation, addr_after_translation);
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.address_translator(Arc::new(translation_rules))
.build()
.await?;
source§impl<K: SessionBuilderKind> GenericSessionBuilder<K>
impl<K: SessionBuilderKind> GenericSessionBuilder<K>
sourcepub fn compression(self, compression: Option<Compression>) -> Self
pub fn compression(self, compression: Option<Compression>) -> Self
Set preferred Compression algorithm. The default is no compression. If it is not supported by database server Session will fall back to no encryption.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.compression(Some(Compression::Snappy))
.build()
.await?;
sourcepub fn schema_agreement_interval(self, timeout: Duration) -> Self
pub fn schema_agreement_interval(self, timeout: Duration) -> Self
Set the delay for schema agreement check. How often driver should ask if schema is in agreement The default is 200 milliseconds.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.schema_agreement_interval(Duration::from_secs(5))
.build()
.await?;
sourcepub fn default_execution_profile_handle(
self,
profile_handle: ExecutionProfileHandle,
) -> Self
pub fn default_execution_profile_handle( self, profile_handle: ExecutionProfileHandle, ) -> Self
Set the default execution profile using its handle
§Example
let execution_profile = ExecutionProfile::builder()
.consistency(Consistency::All)
.request_timeout(Some(Duration::from_secs(2)))
.build();
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.default_execution_profile_handle(execution_profile.into_handle())
.build()
.await?;
sourcepub fn tcp_nodelay(self, nodelay: bool) -> Self
pub fn tcp_nodelay(self, nodelay: bool) -> Self
Set the nodelay TCP flag. The default is true.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.tcp_nodelay(true)
.build()
.await?;
sourcepub fn tcp_keepalive_interval(self, interval: Duration) -> Self
pub fn tcp_keepalive_interval(self, interval: Duration) -> Self
Set the TCP keepalive interval.
The default is None
, which implies that no keepalive messages
are sent on TCP layer when a connection is idle.
Note: CQL-layer keepalives are configured separately,
with Self::keepalive_interval
.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.tcp_keepalive_interval(std::time::Duration::from_secs(42))
.build()
.await?;
sourcepub fn use_keyspace(
self,
keyspace_name: impl Into<String>,
case_sensitive: bool,
) -> Self
pub fn use_keyspace( self, keyspace_name: impl Into<String>, case_sensitive: bool, ) -> Self
Set keyspace to be used on all connections.
Each connection will send "USE <keyspace_name>"
before sending any requests.
This can be later changed with crate::Session::use_keyspace
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.use_keyspace("my_keyspace_name", false)
.build()
.await?;
sourcepub async fn build_legacy(
&self,
) -> Result<GenericSession<LegacyDeserializationApi>, NewSessionError>
👎Deprecated since 0.15.0: Legacy deserialization API is inefficient and is going to be removed soon
pub async fn build_legacy( &self, ) -> Result<GenericSession<LegacyDeserializationApi>, NewSessionError>
Builds the Session after setting all the options.
The new session object uses the legacy deserialization API. If you wish
to use the new API, use SessionBuilder::build
.
§Example
let session: LegacySession = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.compression(Some(Compression::Snappy))
.build_legacy() // Turns SessionBuilder into LegacySession
.await?;
sourcepub async fn build(
&self,
) -> Result<GenericSession<CurrentDeserializationApi>, NewSessionError>
pub async fn build( &self, ) -> Result<GenericSession<CurrentDeserializationApi>, NewSessionError>
Builds the Session after setting all the options.
The new session object uses the new deserialization API. If you wish
to use the old API, use SessionBuilder::build
.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.compression(Some(Compression::Snappy))
.build() // Turns SessionBuilder into Session
.await?;
sourcepub fn connection_timeout(self, duration: Duration) -> Self
pub fn connection_timeout(self, duration: Duration) -> Self
Changes connection timeout The default is 5 seconds. If it’s higher than underlying os’s default connection timeout it won’t effect.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.connection_timeout(Duration::from_secs(30))
.build() // Turns SessionBuilder into Session
.await?;
sourcepub fn pool_size(self, size: PoolSize) -> Self
pub fn pool_size(self, size: PoolSize) -> Self
Sets the per-node connection pool size. The default is one connection per shard, which is the recommended setting for Scylla.
§Example
use std::num::NonZeroUsize;
use scylla::transport::session::PoolSize;
// This session will establish 4 connections to each node.
// For Scylla clusters, this number will be divided across shards
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.pool_size(PoolSize::PerHost(NonZeroUsize::new(4).unwrap()))
.build()
.await?;
sourcepub fn disallow_shard_aware_port(self, disallow: bool) -> Self
pub fn disallow_shard_aware_port(self, disallow: bool) -> Self
If true, prevents the driver from connecting to the shard-aware port, even if the node supports it.
This is a Scylla-specific option. It has no effect on Cassandra clusters.
By default, connecting to the shard-aware port is allowed and, in general, this setting should not be changed. The shard-aware port (19042 or 19142) makes the process of establishing connection per shard more robust compared to the regular transport port (9042 or 9142). With the shard-aware port, the driver is able to choose which shard will be assigned to the connection.
In order to be able to use the shard-aware port effectively, the port needs to be reachable and not behind a NAT which changes source ports (the driver uses the source port to tell Scylla which shard to assign). However, the driver is designed to behave in a robust way if those conditions are not met - if the driver fails to connect to the port or gets a connection to the wrong shard, it will re-attempt the connection to the regular transport port.
The only cost of misconfigured shard-aware port should be a slightly longer reconnection time. If it is unacceptable to you or suspect that it causes you some other problems, you can use this option to disable the shard-aware port feature completely. However, you should use it as a last resort. Before you do that, we strongly recommend that you consider fixing the network issues.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.disallow_shard_aware_port(true)
.build()
.await?;
sourcepub fn keyspaces_to_fetch(
self,
keyspaces: impl IntoIterator<Item = impl Into<String>>,
) -> Self
pub fn keyspaces_to_fetch( self, keyspaces: impl IntoIterator<Item = impl Into<String>>, ) -> Self
Set the keyspaces to be fetched, to retrieve their strategy, and schema metadata if enabled No keyspaces, the default value, means all the keyspaces will be fetched.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.keyspaces_to_fetch(["my_keyspace"])
.build()
.await?;
sourcepub fn fetch_schema_metadata(self, fetch: bool) -> Self
pub fn fetch_schema_metadata(self, fetch: bool) -> Self
Set the fetch schema metadata flag. The default is true.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.fetch_schema_metadata(true)
.build()
.await?;
sourcepub fn keepalive_interval(self, interval: Duration) -> Self
pub fn keepalive_interval(self, interval: Duration) -> Self
Set the keepalive interval.
The default is Some(Duration::from_secs(30))
, which corresponds
to keepalive CQL messages being sent every 30 seconds.
Note: this configures CQL-layer keepalives. See also:
Self::tcp_keepalive_interval
.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.keepalive_interval(std::time::Duration::from_secs(42))
.build()
.await?;
sourcepub fn keepalive_timeout(self, timeout: Duration) -> Self
pub fn keepalive_timeout(self, timeout: Duration) -> Self
Set the keepalive timeout.
The default is Some(Duration::from_secs(30))
. It means that
the connection will be closed if time between sending a keepalive
and receiving a response to any keepalive (not necessarily the same -
it may be one sent later) exceeds 30 seconds.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.keepalive_timeout(std::time::Duration::from_secs(42))
.build()
.await?;
sourcepub fn schema_agreement_timeout(self, timeout: Duration) -> Self
pub fn schema_agreement_timeout(self, timeout: Duration) -> Self
Sets the timeout for waiting for schema agreement. By default, the timeout is 60 seconds.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.schema_agreement_timeout(std::time::Duration::from_secs(120))
.build()
.await?;
sourcepub fn auto_await_schema_agreement(self, enabled: bool) -> Self
pub fn auto_await_schema_agreement(self, enabled: bool) -> Self
Controls automatic waiting for schema agreement after a schema-altering statement is sent. By default, it is enabled.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.auto_await_schema_agreement(false)
.build()
.await?;
sourcepub fn host_filter(self, filter: Arc<dyn HostFilter>) -> Self
pub fn host_filter(self, filter: Arc<dyn HostFilter>) -> Self
Sets the host filter. The host filter decides whether any connections should be opened to the node or not. The driver will also avoid those nodes when re-establishing the control connection.
See the host filter module for a list of pre-defined filters. It is also possible to provide a custom filter by implementing the HostFilter trait.
§Example
// The session will only connect to nodes from "my-local-dc"
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.host_filter(Arc::new(DcHostFilter::new("my-local-dc".to_string())))
.build()
.await?;
sourcepub fn refresh_metadata_on_auto_schema_agreement(
self,
refresh_metadata: bool,
) -> Self
pub fn refresh_metadata_on_auto_schema_agreement( self, refresh_metadata: bool, ) -> Self
Set the refresh metadata on schema agreement flag. The default is true.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.refresh_metadata_on_auto_schema_agreement(true)
.build()
.await?;
sourcepub fn tracing_info_fetch_attempts(self, attempts: NonZeroU32) -> Self
pub fn tracing_info_fetch_attempts(self, attempts: NonZeroU32) -> Self
Set the number of attempts to fetch TracingInfo
in Session::get_tracing_info
.
The default is 5 attempts.
Tracing info might not be available immediately on queried node - that’s why the driver performs a few attempts with sleeps in between.
Cassandra users may want to increase this value - the default is good for Scylla, but Cassandra sometimes needs more time for the data to appear in tracing table.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.tracing_info_fetch_attempts(NonZeroU32::new(10).unwrap())
.build()
.await?;
sourcepub fn tracing_info_fetch_interval(self, interval: Duration) -> Self
pub fn tracing_info_fetch_interval(self, interval: Duration) -> Self
Set the delay between attempts to fetch TracingInfo
in Session::get_tracing_info
.
The default is 3 milliseconds.
Tracing info might not be available immediately on queried node - that’s why the driver performs a few attempts with sleeps in between.
Cassandra users may want to increase this value - the default is good for Scylla, but Cassandra sometimes needs more time for the data to appear in tracing table.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.tracing_info_fetch_interval(Duration::from_millis(50))
.build()
.await?;
sourcepub fn tracing_info_fetch_consistency(self, consistency: Consistency) -> Self
pub fn tracing_info_fetch_consistency(self, consistency: Consistency) -> Self
Set the consistency level of fetching TracingInfo
in Session::get_tracing_info
.
The default is Consistency::One
.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.tracing_info_fetch_consistency(Consistency::One)
.build()
.await?;
sourcepub fn write_coalescing(self, enable: bool) -> Self
pub fn write_coalescing(self, enable: bool) -> Self
If true, the driver will inject a small delay before flushing data to the socket - by rescheduling the task that writes data to the socket. This gives the task an opportunity to collect more write requests and write them in a single syscall, increasing the efficiency.
However, this optimization may worsen latency if the rate of requests issued by the application is low, but otherwise the application is heavily loaded with other tasks on the same tokio executor. Please do performance measurements before committing to disabling this option.
This option is true by default.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.write_coalescing(false) // Enabled by default
.build()
.await?;
sourcepub fn cluster_metadata_refresh_interval(self, interval: Duration) -> Self
pub fn cluster_metadata_refresh_interval(self, interval: Duration) -> Self
Set the interval at which the driver refreshes the cluster metadata which contains information about the cluster topology as well as the cluster schema.
The default is 60 seconds.
In the given example, we have set the duration value to 20 seconds, which means that the metadata is refreshed every 20 seconds.
§Example
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.cluster_metadata_refresh_interval(std::time::Duration::from_secs(20))
.build()
.await?;
sourcepub fn custom_identity(self, identity: SelfIdentity<'static>) -> Self
pub fn custom_identity(self, identity: SelfIdentity<'static>) -> Self
Set the custom identity of the driver/application/instance, to be sent as options in STARTUP message.
By default driver name and version are sent; application name and version and client id are not sent.
§Example
let (app_major, app_minor, app_patch) = (2, 1, 3);
let app_version = format!("{app_major}.{app_minor}.{app_patch}");
let session: Session = SessionBuilder::new()
.known_node("127.0.0.1:9042")
.custom_identity(
SelfIdentity::new()
.with_custom_driver_version("0.13.0-custom_build_17")
.with_application_name("my-app")
.with_application_version(app_version)
)
.build()
.await?;
Trait Implementations§
source§impl<Kind: Clone + SessionBuilderKind> Clone for GenericSessionBuilder<Kind>
impl<Kind: Clone + SessionBuilderKind> Clone for GenericSessionBuilder<Kind>
source§fn clone(&self) -> GenericSessionBuilder<Kind>
fn clone(&self) -> GenericSessionBuilder<Kind>
1.0.0 · source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read moreAuto Trait Implementations§
impl<Kind> Freeze for GenericSessionBuilder<Kind>
impl<Kind> !RefUnwindSafe for GenericSessionBuilder<Kind>
impl<Kind> Send for GenericSessionBuilder<Kind>where
Kind: Send,
impl<Kind> Sync for GenericSessionBuilder<Kind>where
Kind: Sync,
impl<Kind> Unpin for GenericSessionBuilder<Kind>where
Kind: Unpin,
impl<Kind> !UnwindSafe for GenericSessionBuilder<Kind>
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§default unsafe fn clone_to_uninit(&self, dst: *mut T)
default unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)source§impl<T> Instrument for T
impl<T> Instrument for T
source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
source§impl<T> IntoEither for T
impl<T> IntoEither for T
source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moresource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more