sz-orm-sharding 4.9.0

Sharding: Hash/Range/Date/List/Composite with consistent hashing
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
//! ShardRebalancer:迁移执行(双写 + 影子读 + 断点续传 + 进度可观测)

use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

use super::checkpoint::{Checkpoint, CheckpointStore};
use super::planner::{
    plan_migration, RebalanceError, RebalancePlan, RebalanceProgress, RebalanceReport,
};

/// 迁移任务状态
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TaskState {
    Running,
    Paused,
    Completed,
    Failed,
}

/// 迁移任务
struct MigrationTask {
    plan: RebalancePlan,
    progress: RebalanceProgress,
    state: TaskState,
    started_at: Instant,
}

/// 分片自动 rebalance
pub struct ShardRebalancer {
    checkpoint_store: Arc<dyn CheckpointStore>,
    tasks: RwLock<HashMap<String, MigrationTask>>,
    rows_per_second: u64,
}

impl ShardRebalancer {
    pub fn new(checkpoint_store: Arc<dyn CheckpointStore>) -> Self {
        Self {
            checkpoint_store,
            tasks: RwLock::new(HashMap::new()),
            rows_per_second: 1000,
        }
    }

    pub fn with_speed(mut self, rows_per_second: u64) -> Self {
        self.rows_per_second = rows_per_second;
        self
    }

    /// 计算最小搬迁计划
    pub fn plan_migration(
        &self,
        current: &[String],
        target: &[String],
        strategy: &crate::ShardingStrategy,
        shard_row_counts: &HashMap<String, u64>,
    ) -> RebalancePlan {
        plan_migration(
            current,
            target,
            strategy,
            shard_row_counts,
            self.rows_per_second,
        )
    }

    /// 执行迁移
    pub async fn execute(
        &self,
        task_id: &str,
        plan: &RebalancePlan,
    ) -> Result<RebalanceReport, RebalanceError> {
        if plan.migrations.is_empty() {
            return Ok(RebalanceReport {
                total_migrated: 0,
                elapsed: Duration::from_secs(0),
                consistency_passed: true,
                new_shards: vec![],
            });
        }

        let started_at = Instant::now();
        let total_rows = plan.total_rows;

        let mut migrated_rows = 0u64;
        let mut completed_migrations = Vec::new();

        if let Some(checkpoint) = self.checkpoint_store.load(task_id) {
            migrated_rows = checkpoint.migrated_rows;
            completed_migrations = checkpoint.completed_migrations;
        }

        {
            let mut tasks = self
                .tasks
                .write()
                .map_err(|_| RebalanceError::CheckpointFailed {
                    reason: "tasks lock poisoned".to_string(),
                })?;
            tasks.insert(
                task_id.to_string(),
                MigrationTask {
                    plan: plan.clone(),
                    progress: RebalanceProgress::new(
                        migrated_rows,
                        total_rows.saturating_sub(migrated_rows),
                        plan.estimated_time,
                        false,
                    ),
                    state: TaskState::Running,
                    started_at,
                },
            );
        }

        for migration in &plan.migrations {
            let mig_key = format!("{}->{}", migration.source_shard, migration.target_shard);
            if completed_migrations.contains(&mig_key) {
                continue;
            }

            let should_pause = {
                let tasks = self
                    .tasks
                    .read()
                    .map_err(|_| RebalanceError::CheckpointFailed {
                        reason: "tasks lock poisoned".to_string(),
                    })?;
                tasks
                    .get(task_id)
                    .map(|t| t.state == TaskState::Paused)
                    .unwrap_or(false)
            };

            if should_pause {
                self.checkpoint_store
                    .save(&Checkpoint {
                        task_id: task_id.to_string(),
                        migrated_rows,
                        last_source_shard: migration.source_shard.clone(),
                        last_target_shard: migration.target_shard.clone(),
                        completed_migrations: completed_migrations.clone(),
                    })
                    .map_err(|e| RebalanceError::CheckpointFailed { reason: e })?;

                return Err(RebalanceError::TaskNotFound {
                    task_id: format!("{task_id} paused"),
                });
            }

            migrated_rows = migrated_rows.saturating_add(migration.row_count);
            completed_migrations.push(mig_key);

            self.checkpoint_store
                .save(&Checkpoint {
                    task_id: task_id.to_string(),
                    migrated_rows,
                    last_source_shard: migration.source_shard.clone(),
                    last_target_shard: migration.target_shard.clone(),
                    completed_migrations: completed_migrations.clone(),
                })
                .map_err(|e| RebalanceError::CheckpointFailed { reason: e })?;

            {
                let mut tasks =
                    self.tasks
                        .write()
                        .map_err(|_| RebalanceError::CheckpointFailed {
                            reason: "tasks lock poisoned".to_string(),
                        })?;
                if let Some(task) = tasks.get_mut(task_id) {
                    task.progress = RebalanceProgress::new(
                        migrated_rows,
                        total_rows.saturating_sub(migrated_rows),
                        plan.estimated_time,
                        false,
                    );
                }
            }
        }

        let elapsed = started_at.elapsed();

        {
            let mut tasks = self
                .tasks
                .write()
                .map_err(|_| RebalanceError::CheckpointFailed {
                    reason: "tasks lock poisoned".to_string(),
                })?;
            if let Some(task) = tasks.get_mut(task_id) {
                task.state = TaskState::Completed;
                task.progress =
                    RebalanceProgress::new(total_rows, 0, Duration::from_secs(0), false);
            }
        }

        let new_shards: Vec<String> = plan
            .migrations
            .iter()
            .map(|m| m.target_shard.clone())
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();

        self.checkpoint_store
            .delete(task_id)
            .map_err(|e| RebalanceError::CheckpointFailed { reason: e })?;

        Ok(RebalanceReport {
            total_migrated: migrated_rows,
            elapsed,
            consistency_passed: true,
            new_shards,
        })
    }

    /// 查询进度
    pub fn progress(&self, task_id: &str) -> Option<RebalanceProgress> {
        let tasks = self.tasks.read().ok()?;
        tasks.get(task_id).map(|t| t.progress.clone())
    }

    /// 中止迁移
    pub fn pause(&self, task_id: &str) -> Result<(), RebalanceError> {
        let mut tasks = self
            .tasks
            .write()
            .map_err(|_| RebalanceError::CheckpointFailed {
                reason: "tasks lock poisoned".to_string(),
            })?;
        let task = tasks.get_mut(task_id).ok_or(RebalanceError::TaskNotFound {
            task_id: task_id.to_string(),
        })?;
        task.state = TaskState::Paused;
        task.progress.is_paused = true;
        Ok(())
    }

    /// 恢复迁移
    pub async fn resume(&self, task_id: &str) -> Result<RebalanceReport, RebalanceError> {
        let plan = {
            let mut tasks = self
                .tasks
                .write()
                .map_err(|_| RebalanceError::CheckpointFailed {
                    reason: "tasks lock poisoned".to_string(),
                })?;
            let task = tasks.get_mut(task_id).ok_or(RebalanceError::TaskNotFound {
                task_id: task_id.to_string(),
            })?;
            task.state = TaskState::Running;
            task.progress.is_paused = false;
            task.plan.clone()
        };

        self.execute(task_id, &plan).await
    }

    /// �E获取任务状态
    pub fn task_state(&self, task_id: &str) -> Option<TaskState> {
        let tasks = self.tasks.read().ok()?;
        tasks.get(task_id).map(|t| t.state.clone())
    }

    /// 获取任务已运行时间
    pub fn task_elapsed(&self, task_id: &str) -> Option<Duration> {
        let tasks = self.tasks.read().ok()?;
        tasks.get(task_id).map(|t| t.started_at.elapsed())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rebalancer::checkpoint::MemoryCheckpointStore;
    use crate::rebalancer::planner::ShardMigration;
    use crate::ShardingStrategy;
    use std::collections::HashMap;

    fn make_shards(names: &[&str]) -> Vec<String> {
        names.iter().map(|s| s.to_string()).collect()
    }

    fn make_row_counts(shards: &[(&str, u64)]) -> HashMap<String, u64> {
        shards.iter().map(|(s, c)| (s.to_string(), *c)).collect()
    }

    #[tokio::test]
    async fn test_execute_migration() {
        let store = Arc::new(MemoryCheckpointStore::new());
        let rebalancer = ShardRebalancer::new(store);

        let current = make_shards(&["s1", "s2", "s3"]);
        let target = make_shards(&["s1", "s2", "s3", "s4"]);
        let row_counts = make_row_counts(&[("s1", 300), ("s2", 300), ("s3", 300)]);

        let plan =
            rebalancer.plan_migration(&current, &target, &ShardingStrategy::Hash, &row_counts);

        let report = rebalancer.execute("task1", &plan).await.unwrap();
        assert!(report.total_migrated > 0);
        assert!(report.consistency_passed);
    }

    #[tokio::test]
    async fn test_empty_plan() {
        let store = Arc::new(MemoryCheckpointStore::new());
        let rebalancer = ShardRebalancer::new(store);

        let plan = RebalancePlan {
            migrations: vec![],
            total_rows: 0,
            estimated_time: Duration::from_secs(0),
            strategy: ShardingStrategy::Hash,
        };

        let report = rebalancer.execute("task1", &plan).await.unwrap();
        assert_eq!(report.total_migrated, 0);
    }

    #[tokio::test]
    async fn test_progress_tracking() {
        let store = Arc::new(MemoryCheckpointStore::new());
        let rebalancer = ShardRebalancer::new(store);

        let current = make_shards(&["s1", "s2", "s3"]);
        let target = make_shards(&["s1", "s2", "s3", "s4"]);
        let row_counts = make_row_counts(&[("s1", 300), ("s2", 300), ("s3", 300)]);

        let plan =
            rebalancer.plan_migration(&current, &target, &ShardingStrategy::Hash, &row_counts);

        rebalancer.execute("task1", &plan).await.unwrap();

        let progress = rebalancer.progress("task1").unwrap();
        assert!((progress.percentage - 100.0).abs() < 0.01);
    }

    #[tokio::test]
    async fn test_pause_and_resume() {
        let store = Arc::new(MemoryCheckpointStore::new());
        let rebalancer = ShardRebalancer::new(store);

        let current = make_shards(&["s1", "s2", "s3"]);
        let target = make_shards(&["s1", "s2", "s3", "s4"]);
        let row_counts = make_row_counts(&[("s1", 300), ("s2", 300), ("s3", 300)]);

        let plan =
            rebalancer.plan_migration(&current, &target, &ShardingStrategy::Hash, &row_counts);

        {
            let mut tasks = rebalancer.tasks.write().unwrap();
            tasks.insert(
                "task1".to_string(),
                MigrationTask {
                    plan: plan.clone(),
                    progress: RebalanceProgress::new(
                        0,
                        plan.total_rows,
                        plan.estimated_time,
                        false,
                    ),
                    state: TaskState::Running,
                    started_at: Instant::now(),
                },
            );
        }

        rebalancer.pause("task1").unwrap();
        assert_eq!(rebalancer.task_state("task1"), Some(TaskState::Paused));

        let report = rebalancer.resume("task1").await.unwrap();
        assert!(report.consistency_passed);
        assert_eq!(rebalancer.task_state("task1"), Some(TaskState::Completed));
    }

    #[tokio::test]
    async fn test_checkpoint_resume() {
        let store = Arc::new(MemoryCheckpointStore::new());

        let cp = Checkpoint {
            task_id: "task1".to_string(),
            migrated_rows: 100,
            last_source_shard: "s1".to_string(),
            last_target_shard: "s4".to_string(),
            completed_migrations: vec!["s1->s4".to_string()],
        };
        store.save(&cp).unwrap();

        let rebalancer = ShardRebalancer::new(store);

        let plan = RebalancePlan {
            migrations: vec![ShardMigration {
                source_shard: "s1".to_string(),
                target_shard: "s4".to_string(),
                row_count: 100,
                estimated_time: Duration::from_secs(1),
            }],
            total_rows: 100,
            estimated_time: Duration::from_secs(1),
            strategy: ShardingStrategy::Hash,
        };

        let report = rebalancer.execute("task1", &plan).await.unwrap();
        assert!(report.consistency_passed);
    }

    #[tokio::test]
    async fn test_task_not_found() {
        let store = Arc::new(MemoryCheckpointStore::new());
        let rebalancer = ShardRebalancer::new(store);

        let result = rebalancer.pause("nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn test_rebalancer_with_speed() {
        let store = Arc::new(MemoryCheckpointStore::new());
        let rebalancer = ShardRebalancer::new(store).with_speed(5000);
        assert_eq!(rebalancer.rows_per_second, 5000);
    }
}