-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
replica_set.rs
1912 lines (1673 loc) · 67.5 KB
/
replica_set.rs
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::ops::Deref as _;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use futures::future::{self, BoxFuture, Either};
use futures::stream::FuturesUnordered;
use futures::{FutureExt, StreamExt};
use itertools::Itertools;
use rand::seq::SliceRandom as _;
use schemars::JsonSchema;
use segment::types::{
ExtendedPointId, Filter, PointIdType, ScoredPoint, WithPayload, WithPayloadInterface,
WithVector,
};
use serde::{Deserialize, Serialize};
use tokio::runtime::Handle;
use tokio::sync::{Mutex, RwLock};
use super::local_shard::LocalShard;
use super::queue_proxy_shard::QueueProxyShard;
use super::remote_shard::RemoteShard;
use super::resolve::{Resolve, ResolveCondition};
use super::{create_shard_dir, CollectionId};
use crate::config::CollectionConfig;
use crate::operations::consistency_params::{ReadConsistency, ReadConsistencyType};
use crate::operations::point_ops::WriteOrdering;
use crate::operations::shared_storage_config::SharedStorageConfig;
use crate::operations::types::{
CollectionError, CollectionInfo, CollectionResult, CoreSearchRequestBatch, CountRequest,
CountResult, PointRequest, Record, SearchRequestBatch, UpdateResult,
};
use crate::operations::CollectionUpdateOperations;
use crate::save_on_disk::SaveOnDisk;
use crate::shards::channel_service::ChannelService;
use crate::shards::dummy_shard::DummyShard;
use crate::shards::forward_proxy_shard::ForwardProxyShard;
use crate::shards::shard::Shard::{Dummy, ForwardProxy, Local, QueueProxy};
use crate::shards::shard::{PeerId, Shard, ShardId};
use crate::shards::shard_config::ShardConfig;
use crate::shards::shard_trait::ShardOperation;
use crate::shards::telemetry::ReplicaSetTelemetry;
pub type ActivatePeer = Arc<dyn Fn(PeerId, ShardId) + Send + Sync>;
pub type ChangePeerState = Arc<dyn Fn(PeerId, ShardId) + Send + Sync>;
pub type OnPeerCreated = Arc<dyn Fn(PeerId, ShardId) + Send + Sync>;
const DEFAULT_SHARD_DEACTIVATION_TIMEOUT: Duration = Duration::from_secs(30);
const REPLICA_STATE_FILE: &str = "replica_state.json";
// │ Collection Created
// │
// ▼
// ┌──────────────┐
// │ │
// │ Initializing │
// │ │
// └──────┬───────┘
// │ Report created ┌───────────┐
// └────────────────────► │
// Activate │ Consensus │
// ┌─────────────────────┤ │
// │ └───────────┘
// ┌─────▼───────┐ User Promote ┌──────────┐
// │ ◄──────────────────────────► │
// │ Active │ │ Listener │
// │ ◄───────────┐ │ │
// └──┬──────────┘ │Transfer └──┬───────┘
// │ │Finished │
// │ ┌──────┴────────┐ │Update
// │Update │ │ │Failure
// │Failure │ Partial ├───┐ │
// │ │ │ │ │
// │ └───────▲───────┘ │ │
// │ │ │ │
// ┌──▼──────────┐ Transfer │ │ │
// │ │ Started │ │ │
// │ Dead ├────────────┘ │ │
// │ │ │ │
// └─▲───────▲───┘ Transfer │ │
// │ │ Failed/Cancelled│ │
// │ └────────────────────────────┘ │
// │ │
// └─────────────────────────────────────────┘
//
/// State of the single shard within a replica set.
#[derive(Debug, Deserialize, Serialize, JsonSchema, Default, PartialEq, Eq, Hash, Clone, Copy)]
pub enum ReplicaState {
// Active and sound
#[default]
Active,
// Failed for some reason
Dead,
// The shard is partially loaded and is currently receiving data from other shards
Partial,
// Collection is being created
Initializing,
// A shard which receives data, but is not used for search
// Useful for backup shards
Listener,
}
/// Represents a change in replica set, due to scaling of `replication_factor`
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Hash, Clone)]
pub enum Change {
Remove(ShardId, PeerId),
}
/// Represents a replica set state
#[derive(Debug, Deserialize, Serialize, Default, PartialEq, Eq, Clone)]
pub struct ReplicaSetState {
pub is_local: bool,
pub this_peer_id: PeerId,
peers: HashMap<PeerId, ReplicaState>,
}
impl ReplicaSetState {
pub fn get_peer_state(&self, peer_id: &PeerId) -> Option<&ReplicaState> {
self.peers.get(peer_id)
}
pub fn set_peer_state(&mut self, peer_id: PeerId, state: ReplicaState) {
self.peers.insert(peer_id, state);
}
pub fn remove_peer_state(&mut self, peer_id: &PeerId) -> Option<ReplicaState> {
self.peers.remove(peer_id)
}
pub fn peers(&self) -> HashMap<PeerId, ReplicaState> {
self.peers.clone()
}
pub fn active_peers(&self) -> Vec<PeerId> {
self.peers
.iter()
.filter_map(|(peer_id, state)| {
if *state == ReplicaState::Active {
Some(*peer_id)
} else {
None
}
})
.collect()
}
pub fn set_peers(&mut self, peers: HashMap<PeerId, ReplicaState>) {
self.peers = peers;
}
}
/// A set of shard replicas.
/// Handles operations so that the state is consistent across all the replicas of the shard.
/// Prefers local shard for read-only operations.
/// Perform updates on all replicas and report error if there is at least one failure.
///
pub struct ShardReplicaSet {
local: RwLock<Option<Shard>>, // Abstract Shard to be able to use a Proxy during replication
remotes: RwLock<Vec<RemoteShard>>,
replica_state: Arc<SaveOnDisk<ReplicaSetState>>,
/// List of peers that are marked as dead locally, but are not yet submitted to the consensus.
/// List is checked on each consensus round and submitted to the consensus.
/// If the state of the peer is changed in the consensus, it is removed from the list.
/// Update and read operations are not performed on the peers marked as dead.
locally_disabled_peers: parking_lot::RwLock<HashSet<PeerId>>,
pub(crate) shard_path: PathBuf,
pub(crate) shard_id: ShardId,
notify_peer_failure_cb: ChangePeerState,
channel_service: ChannelService,
collection_id: CollectionId,
collection_config: Arc<RwLock<CollectionConfig>>,
shared_storage_config: Arc<SharedStorageConfig>,
update_runtime: Handle,
search_runtime: Handle,
/// Lock to serialized write operations on the replicaset when a write ordering is used.
write_ordering_lock: Mutex<()>,
}
impl ShardReplicaSet {
pub async fn is_local(&self) -> bool {
let local_read = self.local.read().await;
matches!(*local_read, Some(Local(_) | Dummy(_)))
}
pub async fn is_dummy(&self) -> bool {
let local_read = self.local.read().await;
matches!(*local_read, Some(Dummy(_)))
}
pub async fn has_local_shard(&self) -> bool {
self.local.read().await.is_some()
}
pub fn peers(&self) -> HashMap<PeerId, ReplicaState> {
self.replica_state.read().peers()
}
pub fn this_peer_id(&self) -> PeerId {
self.replica_state.read().this_peer_id
}
pub fn highest_replica_peer_id(&self) -> Option<PeerId> {
self.replica_state.read().peers.keys().max().cloned()
}
pub fn highest_alive_replica_peer_id(&self) -> Option<PeerId> {
let read_lock = self.replica_state.read();
let peer_ids = read_lock.peers.keys().cloned().collect::<Vec<_>>();
drop(read_lock);
peer_ids
.into_iter()
.filter(|peer_id| self.peer_is_active(peer_id)) // re-acquire replica_state read lock
.max()
}
pub async fn remote_peers(&self) -> Vec<PeerId> {
self.remotes
.read()
.await
.iter()
.map(|r| r.peer_id)
.collect()
}
pub async fn active_remote_shards(&self) -> Vec<PeerId> {
let replica_state = self.replica_state.read();
let this_peer_id = replica_state.this_peer_id;
replica_state
.active_peers()
.into_iter()
.filter(|peer_id| !self.is_locally_disabled(peer_id) && *peer_id != this_peer_id)
.collect()
}
fn init_remote_shards(
shard_id: ShardId,
collection_id: CollectionId,
state: &ReplicaSetState,
channel_service: &ChannelService,
) -> Vec<RemoteShard> {
state
.peers()
.iter()
.filter(|(peer, _)| **peer != state.this_peer_id)
.map(|(peer_id, _is_active)| {
RemoteShard::new(
shard_id,
collection_id.clone(),
*peer_id,
channel_service.clone(),
)
})
.collect()
}
pub async fn init_empty_local_shard(&self) -> CollectionResult<()> {
let mut local = self.local.write().await;
let current_shard = local.take();
// ToDo: Remove shard files here?
let local_shard_res = LocalShard::build(
self.shard_id,
self.collection_id.clone(),
&self.shard_path,
self.collection_config.clone(),
self.shared_storage_config.clone(),
self.update_runtime.clone(),
)
.await;
match local_shard_res {
Ok(local_shard) => {
*local = Some(Local(local_shard));
Ok(())
}
Err(err) => {
log::error!(
"Failed to initialize local shard {:?}: {err}",
self.shard_path
);
*local = current_shard;
Err(err)
}
}
}
/// Create a new fresh replica set, no previous state is expected.
#[allow(clippy::too_many_arguments)]
pub async fn build(
shard_id: ShardId,
collection_id: CollectionId,
this_peer_id: PeerId,
local: bool,
remotes: HashSet<PeerId>,
on_peer_failure: ChangePeerState,
collection_path: &Path,
collection_config: Arc<RwLock<CollectionConfig>>,
shared_storage_config: Arc<SharedStorageConfig>,
channel_service: ChannelService,
update_runtime: Handle,
search_runtime: Handle,
) -> CollectionResult<Self> {
let shard_path = create_shard_dir(collection_path, shard_id).await?;
let local = if local {
let shard = LocalShard::build(
shard_id,
collection_id.clone(),
&shard_path,
collection_config.clone(),
shared_storage_config.clone(),
update_runtime.clone(),
)
.await?;
Some(Local(shard))
} else {
None
};
let replica_state: SaveOnDisk<ReplicaSetState> =
SaveOnDisk::load_or_init(shard_path.join(REPLICA_STATE_FILE))?;
replica_state.write(|rs| {
rs.this_peer_id = this_peer_id;
if local.is_some() {
rs.is_local = true;
rs.set_peer_state(this_peer_id, ReplicaState::Initializing);
}
for peer in remotes {
rs.set_peer_state(peer, ReplicaState::Initializing);
}
})?;
let remote_shards = Self::init_remote_shards(
shard_id,
collection_id.clone(),
&replica_state.read(),
&channel_service,
);
// Save shard config as the last step, to ensure that the file state is consistent
// Presence of shard config indicates that the shard is ready to be used
let replica_set_shard_config = ShardConfig::new_replica_set();
replica_set_shard_config.save(&shard_path)?;
Ok(Self {
shard_id,
local: RwLock::new(local),
remotes: RwLock::new(remote_shards),
replica_state: replica_state.into(),
locally_disabled_peers: Default::default(),
shard_path,
notify_peer_failure_cb: on_peer_failure,
channel_service,
collection_id,
collection_config,
shared_storage_config,
update_runtime,
search_runtime,
write_ordering_lock: Mutex::new(()),
})
}
pub async fn remove_remote(&self, peer_id: PeerId) -> CollectionResult<()> {
self.replica_state.write(|rs| {
rs.remove_peer_state(&peer_id);
})?;
self.update_locally_disabled(peer_id);
let mut remotes = self.remotes.write().await;
remotes.retain(|remote| remote.peer_id != peer_id);
Ok(())
}
pub async fn add_remote(&self, peer_id: PeerId, state: ReplicaState) -> CollectionResult<()> {
self.replica_state.write(|rs| {
rs.set_peer_state(peer_id, state);
})?;
self.update_locally_disabled(peer_id);
let mut remotes = self.remotes.write().await;
// check remote already exists
if remotes.iter().any(|remote| remote.peer_id == peer_id) {
return Ok(());
}
remotes.push(RemoteShard::new(
self.shard_id,
self.collection_id.clone(),
peer_id,
self.channel_service.clone(),
));
Ok(())
}
pub async fn remove_local(&self) -> CollectionResult<()> {
self.replica_state.write(|rs| {
rs.is_local = false;
let this_peer_id = rs.this_peer_id;
rs.remove_peer_state(&this_peer_id);
})?;
self.update_locally_disabled(self.this_peer_id());
let removing_local = {
let mut local = self.local.write().await;
local.take()
};
if let Some(removing_local) = removing_local {
// stop ongoing tasks and delete data
drop(removing_local);
LocalShard::clear(&self.shard_path).await?;
}
Ok(())
}
pub async fn set_local(
&self,
local: LocalShard,
state: Option<ReplicaState>,
) -> CollectionResult<Option<Shard>> {
let old_shard = self.local.write().await.replace(Local(local));
if !self.replica_state.read().is_local || state.is_some() {
self.replica_state.write(|rs| {
rs.is_local = true;
if let Some(active) = state {
rs.set_peer_state(self.this_peer_id(), active);
}
})?;
}
self.update_locally_disabled(self.this_peer_id());
Ok(old_shard)
}
pub async fn remove_peer(&self, peer_id: PeerId) -> CollectionResult<()> {
if self.this_peer_id() == peer_id {
self.remove_local().await?;
} else {
self.remove_remote(peer_id).await?;
}
Ok(())
}
pub async fn add_peer(&self, peer_id: PeerId, state: ReplicaState) -> CollectionResult<()> {
if self.this_peer_id() == peer_id {
let mut local = self.local.write().await;
let new_local = if local.is_none() {
Some(Local(
LocalShard::build(
self.shard_id,
self.collection_id.clone(),
&self.shard_path,
self.collection_config.clone(),
self.shared_storage_config.clone(),
self.update_runtime.clone(),
)
.await?,
))
} else {
None
};
self.set_replica_state(&peer_id, state)?;
if new_local.is_some() {
*local = new_local;
}
} else {
self.add_remote(peer_id, state).await?;
}
Ok(())
}
/// Recovers shard from disk.
///
/// WARN: This method intended to be used only on the initial start of the node.
/// It does not implement any logic to recover from a failure.
/// Will panic or load partial state if there is a failure.
#[allow(clippy::too_many_arguments)]
pub async fn load(
shard_id: ShardId,
collection_id: CollectionId,
shard_path: &Path,
collection_config: Arc<RwLock<CollectionConfig>>,
shared_storage_config: Arc<SharedStorageConfig>,
channel_service: ChannelService,
on_peer_failure: ChangePeerState,
this_peer_id: PeerId,
update_runtime: Handle,
search_runtime: Handle,
) -> Self {
let replica_state: SaveOnDisk<ReplicaSetState> =
SaveOnDisk::load_or_init(shard_path.join(REPLICA_STATE_FILE)).unwrap();
if replica_state.read().this_peer_id != this_peer_id {
replica_state
.write(|rs| {
let this_peer_id = rs.this_peer_id;
let local_state = rs.remove_peer_state(&this_peer_id);
if let Some(state) = local_state {
rs.set_peer_state(this_peer_id, state);
}
rs.this_peer_id = this_peer_id;
})
.map_err(|e| {
panic!("Failed to update replica state in {shard_path:?}: {e}");
})
.unwrap();
}
let remote_shards: Vec<_> = Self::init_remote_shards(
shard_id,
collection_id.clone(),
&replica_state.read(),
&channel_service,
);
let mut local_load_failure = false;
let local = if replica_state.read().is_local {
let shard = if let Some(recovery_reason) = &shared_storage_config.recovery_mode {
Dummy(DummyShard::new(recovery_reason))
} else {
let res = LocalShard::load(
shard_id,
collection_id.clone(),
shard_path,
collection_config.clone(),
shared_storage_config.clone(),
update_runtime.clone(),
)
.await;
match res {
Ok(shard) => Local(shard),
Err(err) => {
if !shared_storage_config.handle_collection_load_errors {
panic!("Failed to load local shard {shard_path:?}: {err}")
}
local_load_failure = true;
log::error!(
"Failed to load local shard {shard_path:?}, \
initializing \"dummy\" shard instead: \
{err}"
);
Dummy(DummyShard::new(format!(
"Failed to load local shard {shard_path:?}: {err}"
)))
}
}
};
Some(shard)
} else {
None
};
let replica_set = Self {
shard_id,
local: RwLock::new(local),
remotes: RwLock::new(remote_shards),
replica_state: replica_state.into(),
// TODO: move to collection config
locally_disabled_peers: Default::default(),
shard_path: shard_path.to_path_buf(),
notify_peer_failure_cb: on_peer_failure,
channel_service,
collection_id,
collection_config,
shared_storage_config,
update_runtime,
search_runtime,
write_ordering_lock: Mutex::new(()),
};
if local_load_failure && replica_set.active_remote_shards().await.is_empty() {
replica_set
.locally_disabled_peers
.write()
.insert(this_peer_id);
}
replica_set
}
pub fn notify_peer_failure(&self, peer_id: PeerId) {
log::debug!("Notify peer failure: {}", peer_id);
self.notify_peer_failure_cb.deref()(peer_id, self.shard_id)
}
/// Change state of the replica to the given.
/// Ensure that remote shard is initialized.
pub async fn ensure_replica_with_state(
&self,
peer_id: &PeerId,
state: ReplicaState,
) -> CollectionResult<()> {
if *peer_id == self.replica_state.read().this_peer_id {
self.set_replica_state(peer_id, state)?;
} else {
// Create remote shard if necessary
self.add_remote(*peer_id, state).await?;
}
Ok(())
}
pub fn set_replica_state(&self, peer_id: &PeerId, state: ReplicaState) -> CollectionResult<()> {
log::debug!(
"Changing local shard {}:{} state from {:?} to {state:?}",
self.collection_id,
self.shard_id,
self.replica_state.read().get_peer_state(peer_id),
);
self.replica_state.write(|rs| {
if rs.this_peer_id == *peer_id {
rs.is_local = true;
}
rs.set_peer_state(*peer_id, state);
})?;
self.update_locally_disabled(*peer_id);
Ok(())
}
pub async fn apply_state(
&self,
replicas: HashMap<PeerId, ReplicaState>,
) -> CollectionResult<()> {
let old_peers = self.replica_state.read().peers();
self.replica_state.write(|state| {
state.set_peers(replicas.clone());
})?;
self.locally_disabled_peers.write().clear();
let removed_peers = old_peers
.keys()
.filter(|peer_id| !replicas.contains_key(peer_id))
.copied()
.collect::<Vec<_>>();
for peer_id in removed_peers {
self.remove_peer(peer_id).await?;
}
for (peer_id, state) in replicas {
let peer_already_exists = old_peers.get(&peer_id).is_some();
if peer_already_exists {
// do nothing
// We only need to change state and it is already saved
continue;
}
if peer_id == self.this_peer_id() {
// Consensus wants a local replica on this peer
let local_shard = LocalShard::build(
self.shard_id,
self.collection_id.clone(),
&self.shard_path,
self.collection_config.clone(),
self.shared_storage_config.clone(),
self.update_runtime.clone(),
)
.await?;
match state {
ReplicaState::Active => {
// No way we can provide up-to-date replica right away at this point,
// so we report a failure to consensus
self.set_local(local_shard, Some(ReplicaState::Active))
.await?;
self.notify_peer_failure(peer_id);
}
ReplicaState::Dead => {
self.set_local(local_shard, Some(ReplicaState::Dead))
.await?;
}
ReplicaState::Partial => {
self.set_local(local_shard, Some(ReplicaState::Partial))
.await?;
}
ReplicaState::Initializing => {
self.set_local(local_shard, Some(ReplicaState::Initializing))
.await?;
}
ReplicaState::Listener => {
// Same as `Active`, we report a failure to consensus
self.set_local(local_shard, Some(ReplicaState::Listener))
.await?;
self.notify_peer_failure(peer_id);
}
}
continue;
}
// Otherwise it is a missing remote replica, we simply create it
let new_remote = RemoteShard::new(
self.shard_id,
self.collection_id.clone(),
peer_id,
self.channel_service.clone(),
);
self.remotes.write().await.push(new_remote);
}
Ok(())
}
pub fn is_locally_disabled(&self, peer_id: &PeerId) -> bool {
self.locally_disabled_peers.read().contains(peer_id)
}
/// Check whether a peer is registered as `active`.
/// Unknown peers are not active.
pub fn peer_is_active(&self, peer_id: &PeerId) -> bool {
self.peer_state(peer_id) == Some(ReplicaState::Active) && !self.is_locally_disabled(peer_id)
}
pub fn peer_is_active_or_pending(&self, peer_id: &PeerId) -> bool {
let res = match self.peer_state(peer_id) {
Some(ReplicaState::Active) => true,
Some(ReplicaState::Partial) => true,
Some(ReplicaState::Initializing) => true,
Some(ReplicaState::Dead) => false,
Some(ReplicaState::Listener) => true,
None => false,
};
res && !self.is_locally_disabled(peer_id)
}
pub fn peer_state(&self, peer_id: &PeerId) -> Option<ReplicaState> {
self.replica_state.read().get_peer_state(peer_id).copied()
}
/// Execute read op. on replica set:
/// 1 - Prefer local replica
/// 2 - Otherwise uses `read_fan_out_ratio` to compute list of active remote shards.
/// 3 - Fallbacks to all remaining shards if the optimisations fails.
/// It does not report failing peer_ids to the consensus.
pub async fn execute_read_operation<Res, F>(
&self,
read_operation: F,
local_only: bool,
) -> CollectionResult<Res>
where
F: Fn(&(dyn ShardOperation + Send + Sync)) -> BoxFuture<'_, CollectionResult<Res>>,
{
if local_only {
return self.execute_local_read_operation(read_operation).await;
}
let mut responses = self
.execute_cluster_read_operation(read_operation, 1, None)
.await?;
Ok(responses.pop().unwrap())
}
pub async fn execute_and_resolve_read_operation<Res, F>(
&self,
read_operation: F,
read_consistency: Option<ReadConsistency>,
local_only: bool,
) -> CollectionResult<Res>
where
F: Fn(&(dyn ShardOperation + Send + Sync)) -> BoxFuture<'_, CollectionResult<Res>>,
Res: Resolve,
{
if local_only {
return self.execute_local_read_operation(read_operation).await;
}
let read_consistency = read_consistency.unwrap_or_default();
let local_count = usize::from(self.peer_state(&self.this_peer_id()).is_some());
let active_local_count = usize::from(self.peer_is_active(&self.this_peer_id()));
let remotes = self.remotes.read().await;
let remotes_count = remotes.len();
let active_remotes_count = remotes
.iter()
.filter(|remote| self.peer_is_active(&remote.peer_id))
.count();
let total_count = local_count + remotes_count;
let active_count = active_local_count + active_remotes_count;
let (required_successful_results, condition) = match read_consistency {
ReadConsistency::Type(ReadConsistencyType::All) => (total_count, ResolveCondition::All),
ReadConsistency::Type(ReadConsistencyType::Majority) => {
(total_count, ResolveCondition::Majority)
}
ReadConsistency::Type(ReadConsistencyType::Quorum) => {
(total_count / 2 + 1, ResolveCondition::All)
}
ReadConsistency::Factor(factor) => {
(factor.clamp(1, total_count), ResolveCondition::All)
}
};
if active_count < required_successful_results {
return Err(CollectionError::service_error(format!(
"The replica set for shard {} on peer {} does not have enough active replicas",
self.shard_id,
self.this_peer_id(),
)));
}
let mut responses = self
.execute_cluster_read_operation(
read_operation,
required_successful_results,
Some(remotes),
)
.await?;
if responses.len() == 1 {
Ok(responses.pop().unwrap())
} else {
Ok(Res::resolve(responses, condition))
}
}
pub async fn execute_local_read_operation<Res, F>(
&self,
read_operation: F,
) -> CollectionResult<Res>
where
F: Fn(&(dyn ShardOperation + Send + Sync)) -> BoxFuture<'_, CollectionResult<Res>>,
{
let local = self.local.read().await;
let Some(local) = local.deref() else {
return Err(CollectionError::service_error(format!(
"Local shard {} not found",
self.shard_id
)));
};
read_operation(local.get()).await
}
async fn execute_cluster_read_operation<Res, F>(
&self,
read_operation: F,
required_successful_results: usize,
remotes: Option<tokio::sync::RwLockReadGuard<'_, Vec<RemoteShard>>>,
) -> CollectionResult<Vec<Res>>
where
F: Fn(&(dyn ShardOperation + Send + Sync)) -> BoxFuture<'_, CollectionResult<Res>>,
{
let remotes = match remotes {
Some(remotes) => remotes,
None => self.remotes.read().await,
};
let (local, is_local_ready) = match self.local.try_read() {
Ok(local) => {
let is_local_ready = local
.deref()
.as_ref()
.map_or(false, |local| !local.is_update_in_progress());
(future::ready(local).left_future(), is_local_ready)
}
Err(_) => (self.local.read().right_future(), false),
};
let local_is_active = self.peer_is_active(&self.this_peer_id());
let local_operation = if local_is_active {
let local_operation = async {
let local = local.await;
let Some(local) = local.deref() else {
return Err(CollectionError::service_error(format!(
"Local shard {} not found",
self.shard_id
)));
};
read_operation(local.get()).await
};
Some(local_operation.left_future())
} else {
None
};
let mut active_remotes: Vec<_> = remotes
.iter()
.filter(|remote| self.peer_is_active(&remote.peer_id))
.collect();
active_remotes.shuffle(&mut rand::thread_rng());
let remote_operations = active_remotes
.into_iter()
.map(|remote| read_operation(remote).right_future());
let mut operations = local_operation.into_iter().chain(remote_operations);
// Possible scenarios:
//
// - Local is available: default fan-out is 0 (no fan-out, unless explicitly requested)
// - Local is not available: default fan-out is 1
// - There is no local: default fan-out is 1
let default_fan_out = if local_is_active && is_local_ready {
0
} else {
1
};
let read_fan_out_factor: usize = self
.collection_config
.read()
.await
.params
.read_fan_out_factor
.unwrap_or(default_fan_out)
.try_into()
.expect("u32 can be converted into usize");
let initial_concurrent_operations = required_successful_results + read_fan_out_factor;
let mut pending_operations: FuturesUnordered<_> = operations
.by_ref()
.take(initial_concurrent_operations)
.collect();
let mut responses = Vec::new();
let mut errors = Vec::new();
while let Some(result) = pending_operations.next().await {
match result {
Ok(response) => {
responses.push(response);
if responses.len() >= required_successful_results {
break;
}
}
Err(error) => {
if error.is_transient() {
log::debug!("Read operation failed: {error}");
errors.push(error);
} else {
return Err(error);
}
pending_operations.extend(operations.next());
if responses.len() + pending_operations.len() < required_successful_results {
break;
}
}
}
}
if responses.len() >= required_successful_results {
Ok(responses)
} else {
let errors_count = errors.len();
let operations_count = responses.len() + errors.len();
let errors_separator = if !errors.is_empty() { ":" } else { "" };
let mut message = format!(
"{errors_count} of {operations_count} read operations failed{errors_separator}"
);
for error in errors {
write!(&mut message, "\n {error}").expect("writing into String always succeeds");
}
Err(CollectionError::service_error(message))
}
}
pub(crate) async fn on_optimizer_config_update(&self) -> CollectionResult<()> {
let read_local = self.local.read().await;
if let Some(shard) = &*read_local {
shard.on_optimizer_config_update().await