summaryrefslogtreecommitdiff
path: root/crates/utils/tcp_connection/src/instance_incremental_transfer.rs
blob: aeb2cb85fcd7c59945210807f612e57713a5876a (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
use std::path::{Path, PathBuf};

use tokio::fs::{File, OpenOptions, copy, create_dir_all, read, read_to_string, remove_file};
use tokio::io::{AsyncReadExt, AsyncWriteExt, BufWriter};

use crate::{error::TcpTargetError, instance::ConnectionInstance};

// 增量传输协议版本
const INCREMENTAL_TRANSFER_VERSION: u64 = 1;
// 块大小(字节)
const DEFAULT_CHUNK_SIZE: usize = 8192;
// 哈希大小(字节)
const HASH_SIZE: usize = 32; // blake3 produces 32-byte hashes
// 版本文件扩展名
const VERSION_FILE_EXTENSION: &str = "ver";
// 版本历史目录名
const VERSION_HISTORY_DIR: &str = "diff";
// 差异文件扩展名
const DELTA_FILE_EXTENSION: &str = "delta";

// 协议模式常量
const SERVER_DELTA_MODE: u8 = 1;
const SERVER_FULL_MODE: u8 = 2;
const CLIENT_UPDATE_MODE: u8 = 1;
const CLIENT_UPLOAD_MODE: u8 = 2;
const NO_CHANGE_MODE: u8 = 3;

// 协议错误消息
const ERR_INVALID_SERVER_RESPONSE: &str = "Invalid server response format";
const ERR_VERSION_MISMATCH: &str = "Version mismatch detected";
const ERR_CHUNK_INDEX_OUT_OF_BOUNDS: &str = "Chunk index out of bounds";
const ERR_DELTA_FILE_CORRUPTED: &str = "Delta file corrupted or incomplete";

impl ConnectionInstance {
    // ==================== 客户端功能 ====================

    /// 客户端:增量更新到指定版本
    pub async fn client_update_to_version(
        &mut self,
        file_path: impl AsRef<Path>,
        target_version: i32,
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();
        let current_version = self.get_current_version(path).await?;
        println!(
            "Client update: current_version={}, target_version={}",
            current_version, target_version
        );

        if current_version >= target_version {
            println!("Client update: Already up to date, skipping");
            return Ok(()); // 已经是最新版本
        }

        // 发送更新请求
        println!(
            "Client update: Sending protocol version: {}",
            INCREMENTAL_TRANSFER_VERSION
        );
        self.stream
            .write_all(&INCREMENTAL_TRANSFER_VERSION.to_be_bytes())
            .await?;
        println!("Client update: Sending mode: {}", CLIENT_UPDATE_MODE);
        self.stream.write_all(&[CLIENT_UPDATE_MODE]).await?; // 客户端更新模式
        println!("Client update: Sending target version: {}", target_version);
        self.stream.write_all(&target_version.to_be_bytes()).await?;
        self.stream.flush().await?;
        println!("Client update: Request header sent");

        // 执行增量更新
        println!("Client update: Starting incremental update...");
        let result = self
            .client_perform_incremental_update(path, current_version, target_version)
            .await;
        println!(
            "Client update: Incremental update completed, result: {:?}",
            result
        );
        result
    }

    /// 客户端:增量上传变化到服务器
    pub async fn client_upload(
        &mut self,
        file_path: impl AsRef<Path>,
    ) -> Result<i32, TcpTargetError> {
        let path = file_path.as_ref();
        let current_version = self.get_current_version(path).await?;

        // 发送上传请求
        self.stream
            .write_all(&INCREMENTAL_TRANSFER_VERSION.to_be_bytes())
            .await?;
        self.stream.write_all(&[2u8]).await?; // 客户端上传模式
        self.stream
            .write_all(&current_version.to_be_bytes())
            .await?;
        self.stream.flush().await?;

        // 执行增量上传
        let new_version = self
            .client_perform_incremental_upload(path, current_version)
            .await?;

        // 更新本地版本
        self.save_version(path, new_version).await?;

        Ok(new_version)
    }

    // ==================== 服务端功能 ====================

    /// 服务端:处理客户端更新请求
    pub async fn server_handle_client_update(
        &mut self,
        file_path: impl AsRef<Path>,
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();

        println!("Server: Reading protocol version...");
        // 读取协议版本
        let mut version_buf = [0u8; 8];
        self.stream.read_exact(&mut version_buf).await?;
        let version = u64::from_be_bytes(version_buf);
        println!("Server: Received protocol version: {}", version);

        if version != INCREMENTAL_TRANSFER_VERSION {
            return Err(TcpTargetError::Protocol(
                "Unsupported incremental transfer version".to_string(),
            ));
        }

        // 读取请求模式
        let mut mode_buf = [0u8; 1];
        self.stream.read_exact(&mut mode_buf).await?;
        println!("Server: Received mode: {}", mode_buf[0]);

        match mode_buf[0] {
            CLIENT_UPDATE_MODE => {
                // 客户端更新模式
                println!("Server: Client update mode detected");
                let mut version_buf = [0u8; 4];
                self.stream.read_exact(&mut version_buf).await?;
                let target_version = i32::from_be_bytes(version_buf);
                println!("Server: Target version: {}", target_version);

                println!("Server: Sending version delta...");
                let result = self.server_send_version_delta(path, target_version).await;
                println!("Server: Version delta sent, result: {:?}", result);
                result
            }
            CLIENT_UPLOAD_MODE => {
                // 客户端上传模式
                let mut version_buf = [0u8; 4];
                self.stream.read_exact(&mut version_buf).await?;
                let client_version = i32::from_be_bytes(version_buf);

                self.server_receive_client_changes(path, client_version)
                    .await
            }
            _ => {
                return Err(TcpTargetError::Protocol(format!(
                    "{}: unknown mode {}",
                    ERR_INVALID_SERVER_RESPONSE, mode_buf[0]
                )));
            }
        }
    }

    /// 服务端:发送指定版本的增量数据
    pub async fn server_send_delta_to_version(
        &mut self,
        file_path: impl AsRef<Path>,
        from_version: i32,
        to_version: i32,
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();

        // 发送响应头
        self.stream
            .write_all(&INCREMENTAL_TRANSFER_VERSION.to_be_bytes())
            .await?;
        self.stream.write_all(&[1u8]).await?; // 服务端增量模式

        self.server_send_version_delta_internal(path, from_version, to_version)
            .await
    }

    // ==================== 内部实现 ====================

    /// 客户端:执行增量更新
    async fn client_perform_incremental_update(
        &mut self,
        file_path: impl AsRef<Path>,
        current_version: i32,
        target_version: i32,
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();

        // 发送客户端当前版本给服务器
        self.stream
            .write_all(&current_version.to_be_bytes())
            .await?;
        self.stream.flush().await?;

        // 读取服务器响应
        let mut version_buf = [0u8; 8];
        self.stream.read_exact(&mut version_buf).await?;
        let version = u64::from_be_bytes(version_buf);

        if version != INCREMENTAL_TRANSFER_VERSION {
            return Err(TcpTargetError::Protocol(
                "Unsupported incremental transfer version".to_string(),
            ));
        }

        let mut mode_buf = [0u8; 1];
        self.stream.read_exact(&mut mode_buf).await?;

        match mode_buf[0] {
            SERVER_DELTA_MODE => {
                // 服务端增量模式
                self.client_apply_delta(path, target_version).await
            }
            NO_CHANGE_MODE => {
                // 无变化模式,不需要更新
                Ok(())
            }
            _ => Err(TcpTargetError::Protocol(
                "Invalid server response".to_string(),
            )),
        }
    }

    /// 客户端:应用增量数据
    async fn client_apply_delta(
        &mut self,
        file_path: impl AsRef<Path>,
        target_version: i32,
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();

        // 读取增量类型
        let mut delta_type_buf = [0u8; 1];
        self.stream.read_exact(&mut delta_type_buf).await?;

        match delta_type_buf[0] {
            SERVER_FULL_MODE => {
                // 完整文件传输
                self.read_file(path).await?;
            }
            SERVER_DELTA_MODE => {
                // 增量块传输
                self.client_receive_and_apply_chunks(path).await?;
            }
            NO_CHANGE_MODE => {
                // 无变化模式
                // 不需要做任何操作
            }
            _ => {
                return Err(TcpTargetError::Protocol(format!(
                    "{}: unknown mode {}",
                    ERR_INVALID_SERVER_RESPONSE, delta_type_buf[0]
                )));
            }
        }

        // 更新本地版本
        self.save_version(path, target_version).await?;

        // 发送确认
        self.stream.write_all(&[1u8]).await?;
        self.stream.flush().await?;

        Ok(())
    }

    /// 客户端:接收并应用增量块
    async fn client_receive_and_apply_chunks(
        &mut self,
        file_path: impl AsRef<Path>,
    ) -> Result<(), TcpTargetError> {
        self.receive_and_apply_chunks_internal(file_path, None)
            .await
    }

    /// 客户端:执行增量上传
    async fn client_perform_incremental_upload(
        &mut self,
        file_path: impl AsRef<Path>,
        current_version: i32,
    ) -> Result<i32, TcpTargetError> {
        let path = file_path.as_ref();

        // 读取服务器响应
        println!("Client upload: Reading server response version...");
        let mut version_buf = [0u8; 8];
        self.stream.read_exact(&mut version_buf).await?;
        let version = u64::from_be_bytes(version_buf);
        println!("Client upload: Received protocol version: {}", version);

        if version != INCREMENTAL_TRANSFER_VERSION {
            return Err(TcpTargetError::Protocol(
                "Unsupported incremental transfer version".to_string(),
            ));
        }

        println!("Client upload: Reading server response mode...");
        let mut mode_buf = [0u8; 1];
        self.stream.read_exact(&mut mode_buf).await?;
        println!("Client upload: Received mode: {}", mode_buf[0]);

        match mode_buf[0] {
            SERVER_FULL_MODE => {
                // 服务端接收模式
                let new_version = self.client_send_changes(path, current_version).await?;
                Ok(new_version)
            }
            _ => Err(TcpTargetError::Protocol(
                "Invalid server response".to_string(),
            )),
        }
    }

    /// 客户端:发送变化到服务器
    async fn client_send_changes(
        &mut self,
        file_path: impl AsRef<Path>,
        client_version: i32,
    ) -> Result<i32, TcpTargetError> {
        let path = file_path.as_ref();
        println!(
            "Client send changes: Starting to send changes, client_version={}",
            client_version
        );

        // 发送确认给服务器
        println!("Client: Sending acknowledgment to server...");
        self.stream.write_all(&[1u8]).await?;
        self.stream.flush().await?;
        println!("Client: Acknowledgment sent");

        // 发送客户端版本给服务器进行验证
        self.stream.write_all(&client_version.to_be_bytes()).await?;
        self.stream.flush().await?;

        // 计算当前文件块哈希
        let current_hashes = self.calculate_file_chunk_hashes(path).await?;
        println!(
            "Client: Calculated {} current chunk hashes",
            current_hashes.len()
        );

        // 发送块哈希
        println!("Client: Sending chunk hashes to server...");
        match self.send_chunk_hashes(&current_hashes).await {
            Ok(_) => println!("Client: Successfully sent chunk hashes"),
            Err(e) => {
                println!("Client: ERROR sending chunk hashes: {:?}", e);
                return Err(e);
            }
        }
        // Extra flush to ensure data is sent before server reads
        match self.stream.flush().await {
            Ok(_) => println!("Client: Successfully flushed stream"),
            Err(e) => {
                println!("Client: ERROR flushing stream: {:?}", e);
                return Err(e.into());
            }
        }

        // 读取服务器需要的块列表
        println!("Client: Reading chunks needed from server...");
        let chunks_to_send = self.receive_chunks_to_send().await?;
        println!("Client: Received chunks to send: {:?}", chunks_to_send);

        // 发送需要的块
        println!("Client send changes: Sending file chunks to server...");
        self.send_file_chunks(path, &chunks_to_send).await?;
        println!("Client send changes: File chunks sent");

        // 读取新版本号
        println!("Client send changes: Reading new version from server...");
        let mut version_buf = [0u8; 4];
        self.stream.read_exact(&mut version_buf).await?;
        let new_version = i32::from_be_bytes(version_buf);
        println!("Client send changes: Received new version: {}", new_version);

        Ok(new_version)
    }

    /// 服务端:发送版本增量数据
    async fn server_send_version_delta(
        &mut self,
        file_path: impl AsRef<Path>,
        target_version: i32,
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();

        println!("Server send version delta: Reading client version...");
        // 获取客户端当前版本(需要从协议中读取)
        let mut client_version_buf = [0u8; 4];
        self.stream.read_exact(&mut client_version_buf).await?;
        let client_version = i32::from_be_bytes(client_version_buf);
        println!(
            "Server send version delta: Client version: {}",
            client_version
        );

        // 发送响应头
        println!(
            "Server send version delta: Sending protocol version: {}",
            INCREMENTAL_TRANSFER_VERSION
        );
        self.stream
            .write_all(&INCREMENTAL_TRANSFER_VERSION.to_be_bytes())
            .await?;
        println!(
            "Server send version delta: Sending mode: {}",
            SERVER_DELTA_MODE
        );
        self.stream.write_all(&[SERVER_DELTA_MODE]).await?; // 服务端增量模式
        self.stream.flush().await?;
        println!("Server send version delta: Response header sent");

        println!("Server send version delta: Calling internal delta function...");
        let result = self
            .server_send_version_delta_internal(path, client_version, target_version)
            .await;
        println!(
            "Server send version delta: Internal function completed, result: {:?}",
            result
        );
        result
    }

    /// 服务端:内部发送版本增量
    async fn server_send_version_delta_internal(
        &mut self,
        file_path: impl AsRef<Path>,
        from_version: i32,
        to_version: i32,
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();

        println!(
            "Server send version delta internal: from_version={}, to_version={}",
            from_version, to_version
        );

        if from_version == to_version {
            // 版本相同,不需要传输
            println!(
                "Server send version delta internal: Versions are the same, sending NO_CHANGE_MODE"
            );
            self.stream.write_all(&[NO_CHANGE_MODE]).await?; // 无变化模式
            return Ok(());
        }

        // 计算版本间的差异
        println!("Server send version delta internal: Calculating version delta...");
        let delta_chunks = self
            .calculate_version_delta(path, from_version, to_version)
            .await?;
        println!(
            "Server send version delta internal: Delta chunks count: {}",
            delta_chunks.len()
        );

        if delta_chunks.is_empty() {
            // 没有变化或目标版本不存在
            println!("Server send version delta internal: No changes, sending NO_CHANGE_MODE");
            self.stream.write_all(&[NO_CHANGE_MODE]).await?; // 无变化模式
        } else {
            // 发送增量块
            println!(
                "Server send version delta internal: Sending delta chunks with SERVER_DELTA_MODE"
            );
            self.stream.write_all(&[SERVER_DELTA_MODE]).await?; // 增量块模式
            self.send_file_chunks(path, &delta_chunks).await?;
        }
        println!("Server send version delta internal: Completed successfully");
        Ok(())
    }

    /// 服务端:接收客户端变化
    async fn server_receive_client_changes(
        &mut self,
        file_path: impl AsRef<Path>,
        client_version: i32,
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();
        println!("Server receive changes: Client version: {}", client_version);

        // 验证客户端版本是否匹配服务器当前版本
        let server_version = self.get_current_version(path).await?;
        if client_version != server_version {
            return Err(TcpTargetError::Protocol(format!(
                "{}: client {}, server {}",
                ERR_VERSION_MISMATCH, client_version, server_version
            )));
        }

        // 发送响应头
        println!(
            "Server receive changes: Sending protocol version: {}",
            INCREMENTAL_TRANSFER_VERSION
        );
        self.stream
            .write_all(&INCREMENTAL_TRANSFER_VERSION.to_be_bytes())
            .await?;
        println!("Server receive changes: Sending mode: {}", SERVER_FULL_MODE);
        self.stream.write_all(&[SERVER_FULL_MODE]).await?; // 服务端完整文件模式
        self.stream.flush().await?;
        println!("Server receive changes: Response header sent");

        // 接收客户端块哈希
        println!("Server receive changes: Receiving client chunk hashes...");
        // 等待客户端确认
        let mut ack_buf = [0u8; 1];
        self.stream.read_exact(&mut ack_buf).await?;
        if ack_buf[0] != 1 {
            return Err(TcpTargetError::Protocol(
                "Client acknowledgment failed".to_string(),
            ));
        }
        println!("Server receive changes: Client acknowledged, reading client version...");

        // 读取客户端版本进行验证
        let mut client_version_buf = [0u8; 4];
        self.stream.read_exact(&mut client_version_buf).await?;
        let received_client_version = i32::from_be_bytes(client_version_buf);
        println!(
            "Server receive changes: Received client version: {}",
            received_client_version
        );

        // 验证客户端版本是否匹配
        if received_client_version != client_version {
            return Err(TcpTargetError::Protocol(format!(
                "{}: expected {}, got {}",
                ERR_VERSION_MISMATCH, client_version, received_client_version
            )));
        }

        println!("Server receive changes: Reading chunk hashes...");
        let client_chunk_hashes = match self.receive_chunk_hashes().await {
            Ok(hashes) => {
                println!(
                    "Server receive changes: Successfully received {} client chunk hashes",
                    hashes.len()
                );
                hashes
            }
            Err(e) => {
                println!(
                    "Server receive changes: ERROR receiving chunk hashes: {:?}",
                    e
                );
                return Err(e);
            }
        };

        // 计算服务器当前块哈希
        let server_hashes = self.calculate_file_chunk_hashes(path).await?;
        println!(
            "Server: Calculated {} server chunk hashes",
            server_hashes.len()
        );

        // 比较差异,确定需要更新的块
        let chunks_needed = self.compare_chunk_hashes(&client_chunk_hashes, &server_hashes);
        println!(
            "Server: Chunks needed after comparison: {:?}",
            chunks_needed
        );

        // 发送需要的块列表
        println!("Server: Sending chunks needed list: {:?}", chunks_needed);
        self.send_chunks_needed(&chunks_needed).await?;

        // 接收并应用客户端块
        self.receive_and_apply_chunks(path, &chunks_needed).await?;

        // 生成新版本号(这里简化:版本号+1)
        let current_version = self.get_current_version(path).await?;
        let new_version = current_version + 1;

        // 保存差异而不是完整文件
        self.save_version_delta(path, current_version, new_version, &chunks_needed)
            .await?;
        self.save_version(path, new_version).await?;

        // 发送新版本号给客户端
        println!(
            "Server receive changes: Sending new version to client: {}",
            new_version
        );
        self.stream.write_all(&new_version.to_be_bytes()).await?;
        self.stream.flush().await?;
        println!("Server receive changes: New version sent to client");

        Ok(())
    }

    // ==================== 工具函数 ====================

    /// 计算文件的块哈希
    async fn calculate_file_chunk_hashes(
        &self,
        file_path: impl AsRef<Path>,
    ) -> Result<Vec<[u8; HASH_SIZE]>, TcpTargetError> {
        let path = file_path.as_ref();
        let mut file = File::open(path).await?;
        let file_size = file.metadata().await?.len();

        let mut hashes = Vec::new();
        let mut buffer = vec![0u8; DEFAULT_CHUNK_SIZE];
        let mut bytes_read = 0;

        while bytes_read < file_size {
            let bytes_to_read = (file_size - bytes_read).min(DEFAULT_CHUNK_SIZE as u64) as usize;
            let chunk = &mut buffer[..bytes_to_read];

            file.read_exact(chunk).await?;

            let hash = self.simple_chunk_hash(chunk);
            hashes.push(hash);

            bytes_read += bytes_to_read as u64;
        }

        Ok(hashes)
    }

    /// 简单的块哈希函数
    fn simple_chunk_hash(&self, data: &[u8]) -> [u8; HASH_SIZE] {
        // 使用稳定的blake3哈希算法,确保跨平台一致性
        let hash = blake3::hash(data);
        let mut hash_bytes = [0u8; HASH_SIZE];
        hash_bytes[..32].copy_from_slice(hash.as_bytes());
        hash_bytes
    }

    /// 发送块哈希列表
    async fn send_chunk_hashes(
        &mut self,
        hashes: &[[u8; HASH_SIZE]],
    ) -> Result<(), TcpTargetError> {
        let hash_count = hashes.len() as u32;
        println!("Client: Sending {} chunk hashes", hash_count);

        match self.stream.write_all(&hash_count.to_be_bytes()).await {
            Ok(_) => println!("Client: Successfully sent hash count"),
            Err(e) => {
                println!("Client: ERROR sending hash count: {:?}", e);
                return Err(e.into());
            }
        }
        // Extra flush to ensure hash count is sent before server reads
        match self.stream.flush().await {
            Ok(_) => println!("Client: Successfully flushed hash count"),
            Err(e) => {
                println!("Client: ERROR flushing hash count: {:?}", e);
                return Err(e.into());
            }
        }

        for (i, hash) in hashes.iter().enumerate() {
            println!("Client: Sending chunk hash {}: {:?}", i, &hash[..8]); // Show first 8 bytes for debugging
            match self.stream.write_all(hash).await {
                Ok(_) => println!("Client: Successfully sent chunk hash {}", i),
                Err(e) => {
                    println!("Client: ERROR sending chunk hash {}: {:?}", i, e);
                    return Err(e.into());
                }
            }
        }

        match self.stream.flush().await {
            Ok(_) => println!("Client: Successfully flushed after sending hashes"),
            Err(e) => {
                println!("Client: ERROR flushing after sending hashes: {:?}", e);
                return Err(e.into());
            }
        }
        println!("Client: All chunk hashes sent");
        // Extra flush to ensure data is sent before server reads
        match self.stream.flush().await {
            Ok(_) => println!("Client: Successfully flushed final"),
            Err(e) => {
                println!("Client: ERROR flushing final: {:?}", e);
                return Err(e.into());
            }
        }
        Ok(())
    }

    /// 接收块哈希列表
    async fn receive_chunk_hashes(&mut self) -> Result<Vec<[u8; HASH_SIZE]>, TcpTargetError> {
        println!("Server: Starting to receive chunk hashes...");

        let mut count_buf = [0u8; 4];
        println!("Server: Reading chunk hash count...");
        self.stream.read_exact(&mut count_buf).await?;
        let hash_count = u32::from_be_bytes(count_buf) as usize;
        println!(
            "Server: Reading {} chunk hashes, raw bytes: {:?}",
            hash_count, count_buf
        );

        let mut hashes = Vec::with_capacity(hash_count);
        let mut hash_buf = [0u8; HASH_SIZE];

        for i in 0..hash_count {
            println!("Server: Reading chunk hash {}...", i);
            self.stream.read_exact(&mut hash_buf).await?;
            println!("Server: Received chunk hash {}: {:?}", i, &hash_buf[..8]); // Show first 8 bytes for debugging
            hashes.push(hash_buf);
        }

        println!("Server: All {} chunk hashes received", hashes.len());
        Ok(hashes)
    }

    /// 比较块哈希并返回需要更新的块索引
    fn compare_chunk_hashes(
        &self,
        new_hashes: &[[u8; HASH_SIZE]],
        old_hashes: &[[u8; HASH_SIZE]],
    ) -> Vec<usize> {
        let mut chunks_needed = Vec::new();

        for (i, (new_hash, old_hash)) in new_hashes.iter().zip(old_hashes.iter()).enumerate() {
            if new_hash != old_hash {
                chunks_needed.push(i);
            }
        }

        // 如果新文件有更多块,也需要更新
        for i in old_hashes.len()..new_hashes.len() {
            chunks_needed.push(i);
        }

        chunks_needed
    }

    /// 接收需要传输的块列表
    async fn receive_chunks_to_send(&mut self) -> Result<Vec<usize>, TcpTargetError> {
        let mut count_buf = [0u8; 4];
        self.stream.read_exact(&mut count_buf).await?;
        let chunk_count = u32::from_be_bytes(count_buf) as usize;

        let mut chunks = Vec::with_capacity(chunk_count);
        let mut index_buf = [0u8; 4];

        for _ in 0..chunk_count {
            self.stream.read_exact(&mut index_buf).await?;
            let index = u32::from_be_bytes(index_buf) as usize;
            chunks.push(index);
        }

        Ok(chunks)
    }

    /// 发送需要接收的块列表
    async fn send_chunks_needed(&mut self, chunks: &[usize]) -> Result<(), TcpTargetError> {
        let chunk_count = chunks.len() as u32;
        self.stream.write_all(&chunk_count.to_be_bytes()).await?;

        for &chunk_index in chunks {
            self.stream
                .write_all(&(chunk_index as u32).to_be_bytes())
                .await?;
        }

        self.stream.flush().await?;
        Ok(())
    }

    /// 发送指定的文件块
    async fn send_file_chunks(
        &mut self,
        file_path: impl AsRef<Path>,
        chunk_indices: &[usize],
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();
        let mut file = File::open(path).await?;
        let file_size = file.metadata().await?.len();

        // 发送块数量
        self.stream
            .write_all(&(chunk_indices.len() as u32).to_be_bytes())
            .await?;

        if chunk_indices.is_empty() {
            self.stream.flush().await?;
            return Ok(());
        }

        for &chunk_index in chunk_indices {
            let chunk_offset = (chunk_index * DEFAULT_CHUNK_SIZE) as u64;
            if chunk_offset >= file_size {
                continue; // 跳过超出文件范围的块
            }

            // 定位到块位置
            tokio::io::AsyncSeekExt::seek(&mut file, std::io::SeekFrom::Start(chunk_offset))
                .await?;

            // 计算块大小
            let remaining_bytes = file_size - chunk_offset;
            let chunk_size = remaining_bytes.min(DEFAULT_CHUNK_SIZE as u64) as usize;

            // 发送块索引和大小
            self.stream
                .write_all(&(chunk_index as u32).to_be_bytes())
                .await?;
            self.stream
                .write_all(&(chunk_size as u32).to_be_bytes())
                .await?;

            // 发送块数据
            let mut buffer = vec![0u8; chunk_size];
            file.read_exact(&mut buffer).await?;
            self.stream.write_all(&buffer).await?;
        }

        self.stream.flush().await?;
        Ok(())
    }

    /// 接收并应用增量块
    async fn receive_and_apply_chunks(
        &mut self,
        file_path: impl AsRef<Path>,
        chunk_indices: &[usize],
    ) -> Result<(), TcpTargetError> {
        self.receive_and_apply_chunks_internal(file_path, Some(chunk_indices))
            .await
    }

    /// 内部工具函数:接收并应用块数据
    async fn receive_and_apply_chunks_internal(
        &mut self,
        file_path: impl AsRef<Path>,
        expected_indices: Option<&[usize]>,
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();

        // 读取块数量
        let mut count_buf = [0u8; 4];
        self.stream.read_exact(&mut count_buf).await?;
        let chunk_count = u32::from_be_bytes(count_buf) as usize;

        // 创建临时文件来接收完整内容
        let temp_path = path.with_extension("tmp");
        let temp_file = File::create(&temp_path).await?;
        let mut temp_writer = BufWriter::new(temp_file);

        // 记录接收到的块数据
        let mut received_chunks = Vec::new();

        for i in 0..chunk_count {
            // 读取块索引和大小
            let mut index_buf = [0u8; 4];
            self.stream.read_exact(&mut index_buf).await?;
            let chunk_index = u32::from_be_bytes(index_buf) as usize;

            // 验证块索引(如果提供了预期索引)
            if let Some(expected) = expected_indices {
                if i >= expected.len() || chunk_index != expected[i] {
                    return Err(TcpTargetError::Protocol(format!(
                        "{}: expected {:?}, got {}",
                        ERR_CHUNK_INDEX_OUT_OF_BOUNDS,
                        expected.get(i),
                        chunk_index
                    )));
                }
            }

            let mut size_buf = [0u8; 4];
            self.stream.read_exact(&mut size_buf).await?;
            let chunk_size = u32::from_be_bytes(size_buf) as usize;

            // 读取块数据
            let mut chunk_data = vec![0u8; chunk_size];
            self.stream.read_exact(&mut chunk_data).await?;

            // 记录接收到的块
            received_chunks.push((chunk_index, chunk_data));
        }

        // 按块索引排序并写入临时文件
        received_chunks.sort_by_key(|(index, _)| *index);

        for (chunk_index, chunk_data) in received_chunks {
            let chunk_offset = (chunk_index * DEFAULT_CHUNK_SIZE) as u64;
            tokio::io::AsyncSeekExt::seek(&mut temp_writer, std::io::SeekFrom::Start(chunk_offset))
                .await?;
            temp_writer.write_all(&chunk_data).await?;
        }

        temp_writer.flush().await?;

        // 替换原文件
        tokio::fs::rename(&temp_path, path).await?;

        Ok(())
    }

    /// 获取当前文件版本
    async fn get_current_version(
        &self,
        file_path: impl AsRef<Path>,
    ) -> Result<i32, TcpTargetError> {
        let path = file_path.as_ref();
        let version_file_path = path.with_extension(VERSION_FILE_EXTENSION);

        if !version_file_path.exists() {
            return Ok(0); // 默认版本为0
        }

        let version_content = read_to_string(&version_file_path)
            .await
            .map_err(|e| TcpTargetError::File(format!("Failed to read version file: {}", e)))?;

        version_content
            .trim()
            .parse::<i32>()
            .map_err(|e| TcpTargetError::File(format!("Invalid version format: {}", e)))
    }

    /// 保存文件版本
    async fn save_version(
        &self,
        file_path: impl AsRef<Path>,
        version: i32,
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();
        let version_file_path = path.with_extension(VERSION_FILE_EXTENSION);

        tokio::fs::write(&version_file_path, version.to_string())
            .await
            .map_err(|e| TcpTargetError::File(format!("Failed to write version file: {}", e)))?;

        Ok(())
    }

    /// 计算版本间的差异
    async fn calculate_version_delta(
        &self,
        file_path: impl AsRef<Path>,
        from_version: i32,
        to_version: i32,
    ) -> Result<Vec<usize>, TcpTargetError> {
        let path = file_path.as_ref();

        // 如果目标版本不存在,返回空差异
        let current_version = self.get_current_version(path).await?;
        if to_version > current_version {
            return Ok(Vec::new());
        }

        // 获取源版本和目标版本的块哈希
        let from_hashes = self.get_version_chunk_hashes(path, from_version).await?;
        let to_hashes = self.get_version_chunk_hashes(path, to_version).await?;

        // 比较差异
        let delta_chunks = self.compare_chunk_hashes(&to_hashes, &from_hashes);

        Ok(delta_chunks)
    }

    /// 获取指定版本的块哈希
    async fn get_version_chunk_hashes(
        &self,
        file_path: impl AsRef<Path>,
        version: i32,
    ) -> Result<Vec<[u8; HASH_SIZE]>, TcpTargetError> {
        let path = file_path.as_ref();

        if version == 0 {
            // 版本0表示空文件
            return Ok(Vec::new());
        }

        // 从版本历史中重建文件并计算哈希
        let reconstructed_path = self.reconstruct_version(path, version).await?;
        let hashes = self
            .calculate_file_chunk_hashes(&reconstructed_path)
            .await?;

        // 清理临时文件
        let _ = remove_file(&reconstructed_path).await;

        Ok(hashes)
    }

    /// 从差异重建指定版本的文件
    async fn reconstruct_version(
        &self,
        file_path: impl AsRef<Path>,
        target_version: i32,
    ) -> Result<PathBuf, TcpTargetError> {
        let path = file_path.as_ref();
        let temp_path = path.with_extension(format!("temp_{}", target_version));

        if target_version == 0 {
            // 创建空文件
            tokio::fs::write(&temp_path, b"").await?;
            return Ok(temp_path);
        }

        // 从版本0开始,逐步应用差异
        let mut current_version = 0;
        let mut current_path = path.with_extension("temp_base");
        tokio::fs::write(&current_path, b"").await?; // 创建基础空文件

        while current_version < target_version {
            let next_version = current_version + 1;
            let (delta_chunks, chunk_data_list) = self
                .load_version_delta(path, current_version, next_version)
                .await?;

            // 应用差异到新文件
            let next_path = path.with_extension(format!("temp_{}", next_version));
            self.apply_delta_to_file(&current_path, &next_path, &delta_chunks, &chunk_data_list)
                .await?;

            // 清理旧临时文件
            if current_version > 0 {
                let _ = tokio::fs::remove_file(&current_path).await;
            }
            current_path = next_path;
            current_version = next_version;
        }

        Ok(current_path)
    }

    /// 保存版本差异
    async fn save_version_delta(
        &self,
        file_path: impl AsRef<Path>,
        from_version: i32,
        to_version: i32,
        changed_chunks: &[usize],
    ) -> Result<(), TcpTargetError> {
        let path = file_path.as_ref();

        // 创建版本历史目录
        let history_dir = path
            .parent()
            .ok_or_else(|| TcpTargetError::File("Invalid file path".to_string()))?
            .join(VERSION_HISTORY_DIR);

        if !history_dir.exists() {
            create_dir_all(&history_dir).await?;
        }

        // 保存差异信息(记录变化的块索引和实际数据)
        let delta_path = history_dir.join(format!(
            "{}_{}_{}.{}",
            path.file_name()
                .ok_or_else(|| TcpTargetError::File("Invalid file name".to_string()))?
                .to_string_lossy(),
            from_version,
            to_version,
            DELTA_FILE_EXTENSION
        ));

        // 读取当前版本文件以获取变化块的实际数据
        let current_file_data = read(path).await?;

        let mut delta_data = Vec::new();

        for &chunk_index in changed_chunks {
            // 写入块索引
            delta_data.extend_from_slice(&(chunk_index as u32).to_be_bytes());

            // 计算块的起始和结束位置
            let chunk_start = chunk_index * DEFAULT_CHUNK_SIZE;
            let chunk_end =
                std::cmp::min(chunk_start + DEFAULT_CHUNK_SIZE, current_file_data.len());

            // 写入块数据大小
            let chunk_size = (chunk_end - chunk_start) as u32;
            delta_data.extend_from_slice(&chunk_size.to_be_bytes());

            // 写入块数据
            delta_data.extend_from_slice(&current_file_data[chunk_start..chunk_end]);
        }

        tokio::fs::write(&delta_path, &delta_data).await?;

        Ok(())
    }

    /// 加载版本差异
    async fn load_version_delta(
        &self,
        file_path: impl AsRef<Path>,
        from_version: i32,
        to_version: i32,
    ) -> Result<(Vec<usize>, Vec<Vec<u8>>), TcpTargetError> {
        let path = file_path.as_ref();
        let history_dir = path.parent().unwrap().join(VERSION_HISTORY_DIR);

        let delta_path = history_dir.join(format!(
            "{}_{}_{}.{}",
            path.file_name().unwrap().to_string_lossy(),
            from_version,
            to_version,
            DELTA_FILE_EXTENSION
        ));

        if !delta_path.exists() {
            return Ok((Vec::new(), Vec::new()));
        }

        let delta_data = read(&delta_path).await?;
        let mut chunks = Vec::new();
        let mut chunk_data_list = Vec::new();

        let mut offset = 0;
        while offset < delta_data.len() {
            // 读取块索引 (4 bytes)
            if offset + 4 > delta_data.len() {
                return Err(TcpTargetError::File(format!(
                    "{}: incomplete index data",
                    ERR_DELTA_FILE_CORRUPTED
                )));
            }
            let index = u32::from_be_bytes([
                delta_data[offset],
                delta_data[offset + 1],
                delta_data[offset + 2],
                delta_data[offset + 3],
            ]) as usize;
            offset += 4;

            // 读取块大小 (4 bytes)
            if offset + 4 > delta_data.len() {
                return Err(TcpTargetError::File(format!(
                    "{}: incomplete size data",
                    ERR_DELTA_FILE_CORRUPTED
                )));
            }
            let chunk_size = u32::from_be_bytes([
                delta_data[offset],
                delta_data[offset + 1],
                delta_data[offset + 2],
                delta_data[offset + 3],
            ]) as usize;
            offset += 4;

            // 读取块数据
            if offset + chunk_size > delta_data.len() {
                return Err(TcpTargetError::File(format!(
                    "{}: incomplete chunk data",
                    ERR_DELTA_FILE_CORRUPTED
                )));
            }
            let chunk_data = delta_data[offset..offset + chunk_size].to_vec();
            offset += chunk_size;

            chunks.push(index);
            chunk_data_list.push(chunk_data);
        }

        Ok((chunks, chunk_data_list))
    }

    /// 应用差异到文件
    async fn apply_delta_to_file(
        &self,
        source_path: impl AsRef<Path>,
        target_path: impl AsRef<Path>,
        delta_chunks: &[usize],
        chunk_data_list: &[Vec<u8>],
    ) -> Result<(), TcpTargetError> {
        let source_path = source_path.as_ref();
        let target_path = target_path.as_ref();

        // 复制源文件到目标文件
        copy(source_path, target_path).await?;

        if delta_chunks.is_empty() {
            return Ok(());
        }

        // 打开目标文件进行修改
        let mut file = OpenOptions::new().write(true).open(target_path).await?;

        for (i, &chunk_index) in delta_chunks.iter().enumerate() {
            let chunk_offset = (chunk_index * DEFAULT_CHUNK_SIZE) as u64;
            tokio::io::AsyncSeekExt::seek(&mut file, std::io::SeekFrom::Start(chunk_offset))
                .await?;

            // 使用从delta文件中读取的实际块数据进行写入
            if i < chunk_data_list.len() {
                file.write_all(&chunk_data_list[i]).await?;
            }
        }

        Ok(())
    }
}