forked from krojew/cdrs-tokio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeneric_connection.rs
More file actions
298 lines (271 loc) · 9.25 KB
/
generic_connection.rs
File metadata and controls
298 lines (271 loc) · 9.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use cdrs_tokio::cluster::connection_pool::ConnectionPoolConfig;
use cdrs_tokio::cluster::session::{
NodeDistanceEvaluatorWrapper, ReconnectionPolicyWrapper, RetryPolicyWrapper,
DEFAULT_TRANSPORT_BUFFER_SIZE,
};
use cdrs_tokio::cluster::{ConnectionManager, KeyspaceHolder};
use cdrs_tokio::compression::Compression;
use cdrs_tokio::frame::{Envelope, Version};
use cdrs_tokio::frame_encoding::ProtocolFrameEncodingFactory;
use cdrs_tokio::future::BoxFuture;
use cdrs_tokio::load_balancing::node_distance_evaluator::AllLocalNodeDistanceEvaluator;
use cdrs_tokio::retry::ConstantReconnectionPolicy;
use cdrs_tokio::IntoCdrsValue;
use cdrs_tokio::{
authenticators::{SaslAuthenticatorProvider, StaticPasswordAuthenticatorProvider},
cluster::session::Session,
cluster::{GenericClusterConfig, TcpConnectionManager},
error::Result,
load_balancing::RoundRobinLoadBalancingStrategy,
query::*,
query_values,
retry::DefaultRetryPolicy,
transport::TransportTcp,
types::prelude::*,
TryFromRow, TryFromUdt,
};
use futures::FutureExt;
use maplit::hashmap;
use std::{
collections::HashMap,
net::IpAddr,
net::{Ipv4Addr, SocketAddr},
sync::Arc,
};
use tokio::sync::mpsc::Sender;
type CurrentSession = Session<
TransportTcp,
VirtualConnectionManager,
RoundRobinLoadBalancingStrategy<TransportTcp, VirtualConnectionManager>,
>;
/// Implements a cluster configuration where the addresses to
/// connect to are different from the ones configured by replacing
/// the masked part of the address with a different subnet.
///
/// This would allow running your connection through a proxy
/// or mock server while also using a production configuration
/// and having your load balancing configuration be aware of the
/// 'real' addresses.
///
/// This is just a simple use for the generic configuration. By
/// replacing the transport itself you can do much more.
struct VirtualClusterConfig {
authenticator: Arc<dyn SaslAuthenticatorProvider + Sync + Send>,
mask: Ipv4Addr,
actual: Ipv4Addr,
version: Version,
}
fn rewrite(addr: SocketAddr, mask: &Ipv4Addr, actual: &Ipv4Addr) -> SocketAddr {
match addr {
SocketAddr::V4(addr) => {
let virt = addr.ip().octets();
let mask = mask.octets();
let actual = actual.octets();
SocketAddr::new(
IpAddr::V4(Ipv4Addr::new(
(virt[0] & !mask[0]) | (actual[0] & mask[0]),
(virt[1] & !mask[1]) | (actual[1] & mask[1]),
(virt[2] & !mask[2]) | (actual[2] & mask[2]),
(virt[3] & !mask[3]) | (actual[3] & mask[3]),
)),
addr.port(),
)
}
SocketAddr::V6(_) => {
panic!("IpV6 is unsupported!");
}
}
}
struct VirtualConnectionManager {
inner: TcpConnectionManager,
mask: Ipv4Addr,
actual: Ipv4Addr,
}
impl ConnectionManager<TransportTcp> for VirtualConnectionManager {
fn connection(
&self,
event_handler: Option<Sender<Envelope>>,
error_handler: Option<Sender<Error>>,
addr: SocketAddr,
) -> BoxFuture<'_, Result<TransportTcp>> {
self.inner.connection(
event_handler,
error_handler,
rewrite(addr, &self.mask, &self.actual),
)
}
}
impl VirtualConnectionManager {
async fn new(
config: &VirtualClusterConfig,
keyspace_holder: Arc<KeyspaceHolder>,
) -> Result<Self> {
Ok(VirtualConnectionManager {
inner: TcpConnectionManager::new(
config.authenticator.clone(),
keyspace_holder,
Box::<ProtocolFrameEncodingFactory>::default(),
Compression::None,
DEFAULT_TRANSPORT_BUFFER_SIZE,
true,
config.version,
#[cfg(feature = "http-proxy")]
None,
),
mask: config.mask,
actual: config.actual,
})
}
}
impl GenericClusterConfig<TransportTcp, VirtualConnectionManager> for VirtualClusterConfig {
fn create_manager(
&self,
keyspace_holder: Arc<KeyspaceHolder>,
) -> BoxFuture<'_, Result<VirtualConnectionManager>> {
// create a connection manager that points at the rewritten address so that's where it connects, but
// then return a manager with the 'virtual' address for internal purposes.
VirtualConnectionManager::new(self, keyspace_holder).boxed()
}
fn event_channel_capacity(&self) -> usize {
32
}
fn version(&self) -> Version {
self.version
}
fn connection_pool_config(&self) -> ConnectionPoolConfig {
Default::default()
}
}
#[tokio::main]
async fn main() {
let user = "user";
let password = "password";
let authenticator = Arc::new(StaticPasswordAuthenticatorProvider::new(&user, &password));
let mask = Ipv4Addr::new(255, 255, 255, 0);
let actual = Ipv4Addr::new(127, 0, 0, 0);
let reconnection_policy = Arc::new(ConstantReconnectionPolicy::default());
let cluster_config = VirtualClusterConfig {
authenticator,
mask,
actual,
version: Version::V5,
};
let nodes = [
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)), 9042),
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)), 9043),
];
let load_balancing = RoundRobinLoadBalancingStrategy::new();
let mut session = cdrs_tokio::cluster::connect_generic(
&cluster_config,
nodes,
load_balancing,
RetryPolicyWrapper(Box::<DefaultRetryPolicy>::default()),
ReconnectionPolicyWrapper(reconnection_policy),
NodeDistanceEvaluatorWrapper(Box::<AllLocalNodeDistanceEvaluator>::default()),
None,
)
.await
.expect("session should be created");
create_keyspace(&mut session).await;
create_udt(&mut session).await;
create_table(&mut session).await;
insert_struct(&mut session).await;
select_struct(&mut session).await;
update_struct(&mut session).await;
delete_struct(&mut session).await;
}
#[derive(Clone, Debug, IntoCdrsValue, TryFromRow, PartialEq)]
struct RowStruct {
key: i32,
user: User,
map: HashMap<String, User>,
list: Vec<User>,
}
impl RowStruct {
fn into_query_values(self) -> QueryValues {
query_values!("key" => self.key, "user" => self.user, "map" => self.map, "list" => self.list)
}
}
#[derive(Debug, Clone, PartialEq, IntoCdrsValue, TryFromUdt)]
struct User {
username: String,
}
async fn create_keyspace(session: &mut CurrentSession) {
let create_ks: &'static str = "CREATE KEYSPACE IF NOT EXISTS test_ks WITH REPLICATION = { \
'class' : 'SimpleStrategy', 'replication_factor' : 1 };";
session
.query(create_ks)
.await
.expect("Keyspace creation error");
}
async fn create_udt(session: &mut CurrentSession) {
let create_type_cql = "CREATE TYPE IF NOT EXISTS test_ks.user (username text)";
session
.query(create_type_cql)
.await
.expect("Keyspace creation error");
}
async fn create_table(session: &mut CurrentSession) {
let create_table_cql =
"CREATE TABLE IF NOT EXISTS test_ks.my_test_table (key int PRIMARY KEY, \
user frozen<test_ks.user>, map map<text, frozen<test_ks.user>>, list list<frozen<test_ks.user>>);";
session
.query(create_table_cql)
.await
.expect("Table creation error");
}
//noinspection DuplicatedCode
async fn insert_struct(session: &mut CurrentSession) {
let row = RowStruct {
key: 3i32,
user: User {
username: "John".to_string(),
},
map: hashmap! { "John".to_string() => User { username: "John".to_string() } },
list: vec![User {
username: "John".to_string(),
}],
};
let insert_struct_cql = "INSERT INTO test_ks.my_test_table \
(key, user, map, list) VALUES (?, ?, ?, ?)";
session
.query_with_values(insert_struct_cql, row.into_query_values())
.await
.expect("insert");
}
//noinspection DuplicatedCode
async fn select_struct(session: &mut CurrentSession) {
let select_struct_cql = "SELECT * FROM test_ks.my_test_table";
let rows = session
.query(select_struct_cql)
.await
.expect("query")
.response_body()
.expect("get body")
.into_rows()
.expect("into rows");
for row in rows {
let my_row: RowStruct = RowStruct::try_from_row(row).expect("into RowStruct");
println!("struct got: {my_row:?}");
}
}
//noinspection DuplicatedCode
async fn update_struct(session: &mut CurrentSession) {
let update_struct_cql = "UPDATE test_ks.my_test_table SET user = ? WHERE key = ?";
let upd_user = User {
username: "Marry".to_string(),
};
let user_key = 1i32;
session
.query_with_values(update_struct_cql, query_values!(upd_user, user_key))
.await
.expect("update");
}
async fn delete_struct(session: &mut CurrentSession) {
let delete_struct_cql = "DELETE FROM test_ks.my_test_table WHERE key = ?";
let user_key = 1i32;
session
.query_with_values(delete_struct_cql, query_values!(user_key))
.await
.expect("delete");
}