fluss-rs 0.1.0

The official rust client of Apache Fluss (Incubating)
Documentation
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use crate::cluster::{BucketLocation, ServerNode, ServerType};
use crate::error::{Error, Result};
use crate::metadata::{
    JsonSerde, PhysicalTablePath, TableBucket, TableDescriptor, TableInfo, TablePath,
};
use crate::proto::{MetadataResponse, PbBucketMetadata};
use crate::rpc::{from_pb_server_node, from_pb_table_path};
use crate::{BucketId, PartitionId, TableId};
use rand::random_range;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

static EMPTY: Vec<BucketLocation> = Vec::new();

#[derive(Default)]
pub struct Cluster {
    coordinator_server: Option<ServerNode>,
    alive_tablet_servers_by_id: HashMap<i32, ServerNode>,
    alive_tablet_servers: Vec<ServerNode>,
    available_locations_by_path: HashMap<Arc<PhysicalTablePath>, Vec<BucketLocation>>,
    available_locations_by_bucket: HashMap<TableBucket, BucketLocation>,
    table_id_by_path: HashMap<TablePath, TableId>,
    table_path_by_id: HashMap<TableId, TablePath>,
    table_info_by_path: HashMap<TablePath, TableInfo>,
    partitions_id_by_path: HashMap<Arc<PhysicalTablePath>, PartitionId>,
    partition_name_by_id: HashMap<PartitionId, String>,
}

impl Cluster {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        coordinator_server: Option<ServerNode>,
        alive_tablet_servers_by_id: HashMap<i32, ServerNode>,
        available_locations_by_path: HashMap<Arc<PhysicalTablePath>, Vec<BucketLocation>>,
        available_locations_by_bucket: HashMap<TableBucket, BucketLocation>,
        table_id_by_path: HashMap<TablePath, TableId>,
        table_info_by_path: HashMap<TablePath, TableInfo>,
        partitions_id_by_path: HashMap<Arc<PhysicalTablePath>, PartitionId>,
    ) -> Self {
        let alive_tablet_servers = alive_tablet_servers_by_id.values().cloned().collect();
        let table_path_by_id = table_id_by_path
            .iter()
            .map(|(path, table_id)| (*table_id, path.clone()))
            .collect();
        let partition_name_by_id = partitions_id_by_path
            .iter()
            .filter_map(|(path, id)| path.get_partition_name().map(|name| (*id, name.clone())))
            .collect();
        Cluster {
            coordinator_server,
            alive_tablet_servers_by_id,
            alive_tablet_servers,
            available_locations_by_path,
            available_locations_by_bucket,
            table_id_by_path,
            table_path_by_id,
            table_info_by_path,
            partitions_id_by_path,
            partition_name_by_id,
        }
    }

    pub fn invalidate_server(&self, server_id: &i32, table_ids: Vec<TableId>) -> Self {
        let alive_tablet_servers_by_id = self
            .alive_tablet_servers_by_id
            .iter()
            .filter(|&(id, _)| id != server_id)
            .map(|(id, ts)| (*id, ts.clone()))
            .collect();

        let table_paths: HashSet<&TablePath> = table_ids
            .iter()
            .filter_map(|id| self.table_path_by_id.get(id))
            .collect();

        let (available_locations_by_path, available_locations_by_bucket) =
            self.filter_bucket_locations_by_path(&table_paths);

        Cluster::new(
            self.coordinator_server.clone(),
            alive_tablet_servers_by_id,
            available_locations_by_path,
            available_locations_by_bucket,
            self.table_id_by_path.clone(),
            self.table_info_by_path.clone(),
            self.partitions_id_by_path.clone(),
        )
    }

    pub fn invalidate_physical_table_meta(
        &self,
        physical_tables_to_invalid: &HashSet<PhysicalTablePath>,
    ) -> Self {
        let table_paths: HashSet<&TablePath> = physical_tables_to_invalid
            .iter()
            .map(|path| path.get_table_path())
            .collect();
        let (available_locations_by_path, available_locations_by_bucket) =
            self.filter_bucket_locations_by_path(&table_paths);

        Cluster::new(
            self.coordinator_server.clone(),
            self.alive_tablet_servers_by_id.clone(),
            available_locations_by_path,
            available_locations_by_bucket,
            self.table_id_by_path.clone(),
            self.table_info_by_path.clone(),
            self.partitions_id_by_path.clone(),
        )
    }

    pub fn update(&mut self, cluster: Cluster) {
        let Cluster {
            coordinator_server,
            alive_tablet_servers_by_id,
            alive_tablet_servers,
            available_locations_by_path,
            available_locations_by_bucket,
            table_id_by_path,
            table_path_by_id,
            table_info_by_path,
            partitions_id_by_path,
            partition_name_by_id,
        } = cluster;
        self.coordinator_server = coordinator_server;
        self.alive_tablet_servers_by_id = alive_tablet_servers_by_id;
        self.alive_tablet_servers = alive_tablet_servers;
        self.available_locations_by_path = available_locations_by_path;
        self.available_locations_by_bucket = available_locations_by_bucket;
        self.table_id_by_path = table_id_by_path;
        self.table_path_by_id = table_path_by_id;
        self.table_info_by_path = table_info_by_path;
        self.partitions_id_by_path = partitions_id_by_path;
        self.partition_name_by_id = partition_name_by_id;
    }

    fn filter_bucket_locations_by_path(
        &self,
        table_paths: &HashSet<&TablePath>,
    ) -> (
        HashMap<Arc<PhysicalTablePath>, Vec<BucketLocation>>,
        HashMap<TableBucket, BucketLocation>,
    ) {
        let available_locations_by_path = self
            .available_locations_by_path
            .iter()
            .filter(|&(path, _)| !table_paths.contains(path.get_table_path()))
            .map(|(path, locations)| (path.clone(), locations.clone()))
            .collect();

        let available_locations_by_bucket = self
            .available_locations_by_bucket
            .iter()
            .filter(|&(_bucket, location)| {
                !table_paths.contains(&location.physical_table_path.get_table_path())
            })
            .map(|(bucket, location)| (bucket.clone(), location.clone()))
            .collect();

        (available_locations_by_path, available_locations_by_bucket)
    }

    pub fn from_metadata_response(
        metadata_response: MetadataResponse,
        origin_cluster: Option<&Cluster>,
    ) -> Result<Cluster> {
        let mut servers = HashMap::with_capacity(metadata_response.tablet_servers.len());
        for pb_server in metadata_response.tablet_servers {
            let server_id = pb_server.node_id;
            let server_node = from_pb_server_node(pb_server, ServerType::TabletServer);
            servers.insert(server_id, server_node);
        }

        let coordinator_server = metadata_response
            .coordinator_server
            .map(|node| from_pb_server_node(node, ServerType::CoordinatorServer));

        let mut table_id_by_path = HashMap::new();
        let mut table_info_by_path = HashMap::new();
        let mut partitions_id_by_path = HashMap::new();
        let mut tmp_available_locations_by_path = HashMap::new();
        let mut tmp_available_location_by_bucket = HashMap::new();

        if let Some(origin) = origin_cluster {
            table_info_by_path.extend(origin.get_table_info_by_path().clone());
            table_id_by_path.extend(origin.get_table_id_by_path().clone());
            partitions_id_by_path.extend(origin.partitions_id_by_path.clone());
            tmp_available_locations_by_path.extend(origin.available_locations_by_path.clone());
            tmp_available_location_by_bucket.extend(origin.available_locations_by_bucket.clone());
        }

        // iterate all table metadata
        for table_metadata in metadata_response.table_metadata {
            let table_id = table_metadata.table_id;
            let table_path = from_pb_table_path(&table_metadata.table_path);
            let table_descriptor = TableDescriptor::deserialize_json(
                &serde_json::from_slice(table_metadata.table_json.as_slice()).map_err(|e| {
                    Error::JsonSerdeError {
                        message: format!(
                            "Error deserializing table_json into TableDescriptor for table_id {table_id} and table_path {table_path}: {e}"
                        )
                    }
                })?,
            )?;
            let table_info = TableInfo::of(
                table_path.clone(),
                table_id,
                table_metadata.schema_id,
                table_descriptor,
                table_metadata.created_time,
                table_metadata.modified_time,
            );
            table_info_by_path.insert(table_path.clone(), table_info);
            table_id_by_path.insert(table_path.clone(), table_id);

            let bucket_metadata = table_metadata.bucket_metadata;
            let physical_table_path = Arc::new(PhysicalTablePath::of(Arc::new(table_path.clone())));

            let bucket_locations = get_bucket_locations(
                &mut servers,
                bucket_metadata.as_slice(),
                table_id,
                None,
                &physical_table_path,
            );
            tmp_available_locations_by_path.insert(physical_table_path, bucket_locations);
        }

        // iterate all partition metadata
        for partition_metadata in metadata_response.partition_metadata {
            let table_id = partition_metadata.table_id;

            if let Some(cluster) = origin_cluster {
                let partition_name = partition_metadata.partition_name;
                let table_path = cluster.get_table_path_by_id(table_id).unwrap();
                let partition_id = partition_metadata.partition_id;

                let physical_table_path = Arc::new(PhysicalTablePath::of_partitioned(
                    Arc::new(table_path.clone()),
                    Some(partition_name),
                ));

                partitions_id_by_path.insert(Arc::clone(&physical_table_path), partition_id);

                let bucket_locations = get_bucket_locations(
                    &mut servers,
                    partition_metadata.bucket_metadata.as_slice(),
                    table_id,
                    Some(partition_id),
                    &physical_table_path,
                );

                tmp_available_locations_by_path.insert(physical_table_path, bucket_locations);
            }
        }

        for bucket_locations in &mut tmp_available_locations_by_path.values() {
            for location in bucket_locations {
                if location.leader().is_some() {
                    tmp_available_location_by_bucket
                        .insert(location.table_bucket.clone(), location.clone());
                }
            }
        }

        Ok(Cluster::new(
            coordinator_server,
            servers,
            tmp_available_locations_by_path,
            tmp_available_location_by_bucket,
            table_id_by_path,
            table_info_by_path,
            partitions_id_by_path,
        ))
    }

    pub fn get_coordinator_server(&self) -> Option<&ServerNode> {
        self.coordinator_server.as_ref()
    }

    pub fn leader_for(&self, table_bucket: &TableBucket) -> Option<&ServerNode> {
        let location = self.available_locations_by_bucket.get(table_bucket);
        if let Some(location) = location {
            location.leader().as_ref()
        } else {
            None
        }
    }

    pub fn get_tablet_server(&self, id: i32) -> Option<&ServerNode> {
        self.alive_tablet_servers_by_id.get(&id)
    }

    pub fn get_table_bucket(
        &self,
        physical_table_path: &PhysicalTablePath,
        bucket_id: BucketId,
    ) -> Result<TableBucket> {
        let table_info = self.get_table(physical_table_path.get_table_path())?;
        let partition_id = self.get_partition_id(physical_table_path);

        if physical_table_path.get_partition_name().is_some() && partition_id.is_none() {
            return Err(Error::partition_not_exist(format!(
                "The partition {} is not found in cluster",
                physical_table_path.get_partition_name().unwrap()
            )));
        }

        Ok(TableBucket::new_with_partition(
            table_info.table_id,
            partition_id,
            bucket_id,
        ))
    }

    pub fn get_partition_id(&self, physical_table_path: &PhysicalTablePath) -> Option<PartitionId> {
        self.partitions_id_by_path.get(physical_table_path).copied()
    }

    pub fn get_partition_name(&self, partition_id: PartitionId) -> Option<&String> {
        self.partition_name_by_id.get(&partition_id)
    }

    pub fn get_table_id(&self, table_path: &TablePath) -> Option<i64> {
        self.table_id_by_path.get(table_path).copied()
    }

    pub fn get_bucket_locations_by_path(
        &self,
    ) -> &HashMap<Arc<PhysicalTablePath>, Vec<BucketLocation>> {
        &self.available_locations_by_path
    }

    pub fn get_table_info_by_path(&self) -> &HashMap<TablePath, TableInfo> {
        &self.table_info_by_path
    }

    pub fn get_table_id_by_path(&self) -> &HashMap<TablePath, i64> {
        &self.table_id_by_path
    }

    pub fn get_table_path_by_id(&self, table_id: TableId) -> Option<&TablePath> {
        self.table_path_by_id.get(&table_id)
    }

    pub fn get_available_buckets_for_table_path(
        &self,
        table_path: &PhysicalTablePath,
    ) -> &Vec<BucketLocation> {
        self.available_locations_by_path
            .get(table_path)
            .unwrap_or(&EMPTY)
    }

    pub fn get_server_nodes(&self) -> Vec<ServerNode> {
        let mut nodes = Vec::new();
        if let Some(coordinator) = &self.coordinator_server {
            nodes.push(coordinator.clone());
        }
        nodes.extend(self.alive_tablet_servers.iter().cloned());
        nodes
    }

    pub fn get_one_available_server(&self) -> Option<&ServerNode> {
        if self.alive_tablet_servers.is_empty() {
            return None;
        }
        let offset = random_range(0..self.alive_tablet_servers.len());
        self.alive_tablet_servers.get(offset)
    }

    pub fn get_bucket_count(&self, table_path: &TablePath) -> i32 {
        self.table_info_by_path
            .get(table_path)
            .unwrap_or_else(|| panic!("can't not table info by path {table_path}"))
            .num_buckets
    }

    pub fn get_table(&self, table_path: &TablePath) -> Result<&TableInfo> {
        self.table_info_by_path
            .get(table_path)
            .ok_or_else(|| Error::invalid_table(format!("Table info not found for {table_path}")))
    }

    pub fn opt_get_table(&self, table_path: &TablePath) -> Option<&TableInfo> {
        self.table_info_by_path.get(table_path)
    }

    pub fn get_partition_id_by_path(&self) -> &HashMap<Arc<PhysicalTablePath>, PartitionId> {
        &self.partitions_id_by_path
    }
}

fn get_bucket_locations(
    servers: &mut HashMap<i32, ServerNode>,
    bucket_metadata: &[PbBucketMetadata],
    table_id: i64,
    partition_id: Option<PartitionId>,
    physical_table_path: &Arc<PhysicalTablePath>,
) -> Vec<BucketLocation> {
    let mut bucket_locations = Vec::new();
    for metadata in bucket_metadata {
        let bucket_id = metadata.bucket_id;
        let bucket = TableBucket::new_with_partition(table_id, partition_id, bucket_id);

        let server = if let Some(leader_id) = metadata.leader_id
            && let Some(server_node) = servers.get(&leader_id)
        {
            Some(server_node.clone())
        } else {
            None
        };

        bucket_locations.push(BucketLocation::new(
            bucket.clone(),
            server,
            Arc::clone(physical_table_path),
        ));
    }
    bucket_locations
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_coordinator() -> ServerNode {
        ServerNode::new(
            0,
            "coord-host".to_string(),
            9123,
            ServerType::CoordinatorServer,
        )
    }

    fn make_tablet_servers() -> HashMap<i32, ServerNode> {
        let mut servers = HashMap::new();
        servers.insert(
            1,
            ServerNode::new(1, "ts1-host".to_string(), 9124, ServerType::TabletServer),
        );
        servers.insert(
            2,
            ServerNode::new(2, "ts2-host".to_string(), 9125, ServerType::TabletServer),
        );
        servers
    }

    #[test]
    fn test_server_node_getters() {
        let node = ServerNode::new(5, "myhost".to_string(), 8080, ServerType::TabletServer);
        assert_eq!(node.id(), 5);
        assert_eq!(node.host(), "myhost");
        assert_eq!(node.port(), 8080);
        assert_eq!(node.server_type(), &ServerType::TabletServer);
        assert_eq!(node.uid(), "ts-5");
        assert_eq!(node.url(), "myhost:8080");
    }

    #[test]
    fn test_server_type_display() {
        assert_eq!(ServerType::TabletServer.to_string(), "TabletServer");
        assert_eq!(
            ServerType::CoordinatorServer.to_string(),
            "CoordinatorServer"
        );
    }

    #[test]
    fn test_get_server_nodes_with_coordinator_and_tablets() {
        let cluster = Cluster::new(
            Some(make_coordinator()),
            make_tablet_servers(),
            HashMap::new(),
            HashMap::new(),
            HashMap::new(),
            HashMap::new(),
            HashMap::new(),
        );

        let nodes = cluster.get_server_nodes();
        assert_eq!(nodes.len(), 3);

        let coordinator_count = nodes
            .iter()
            .filter(|n| *n.server_type() == ServerType::CoordinatorServer)
            .count();
        assert_eq!(coordinator_count, 1);

        let tablet_count = nodes
            .iter()
            .filter(|n| *n.server_type() == ServerType::TabletServer)
            .count();
        assert_eq!(tablet_count, 2);
    }

    #[test]
    fn test_get_server_nodes_no_coordinator() {
        let cluster = Cluster::new(
            None,
            make_tablet_servers(),
            HashMap::new(),
            HashMap::new(),
            HashMap::new(),
            HashMap::new(),
            HashMap::new(),
        );

        let nodes = cluster.get_server_nodes();
        assert_eq!(nodes.len(), 2);
        assert!(
            nodes
                .iter()
                .all(|n| *n.server_type() == ServerType::TabletServer)
        );
    }

    #[test]
    fn test_get_server_nodes_empty_cluster() {
        let cluster = Cluster::default();
        let nodes = cluster.get_server_nodes();
        assert!(nodes.is_empty());
    }
}