cooklang_sync_client/
chunker.rs1use log::trace;
2use quick_cache::{sync::Cache, Weighter};
3use sha2::{Digest, Sha256};
4use std::path::{Path, PathBuf};
5use tokio::fs::{self, create_dir_all, File};
6use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader, BufWriter};
7
8use crate::errors::SyncError;
9
10const BINARY_CHUNK_SIZE: usize = 1_024 * 1_024; const BINARY_HASH_SIZE: usize = 32;
12const TEXT_HASH_SIZE: usize = 10;
13
14pub struct Chunker {
15 cache: InMemoryCache,
16 base_path: PathBuf,
17}
18
19type Result<T, E = SyncError> = std::result::Result<T, E>;
20
21impl Chunker {
22 pub fn new(cache: InMemoryCache, base_path: PathBuf) -> Chunker {
23 Chunker { cache, base_path }
24 }
25
26 fn full_path(&self, path: &str) -> PathBuf {
27 let mut base = self.base_path.clone();
28 base.push(path);
29 base
30 }
31
32 pub async fn hashify(&mut self, path: &str) -> Result<Vec<String>> {
33 let p = Path::new(path);
34
35 if is_text(p) {
37 self.hashify_text(path).await
38 } else if is_binary(p) {
39 self.hashify_binary(path).await
40 } else {
41 Err(SyncError::UnlistedFileFormat(path.to_string()))
42 }
43 }
44
45 async fn hashify_binary(&mut self, path: &str) -> Result<Vec<String>> {
46 let file = File::open(self.full_path(path))
47 .await
48 .map_err(|e| SyncError::from_io_error(path, e))?;
49 let mut reader = BufReader::new(file);
50 let mut hashes = Vec::new();
51 let mut buffer = vec![0u8; BINARY_CHUNK_SIZE];
52
53 loop {
54 let bytes_read = reader
55 .read(&mut buffer)
56 .await
57 .map_err(|e| SyncError::from_io_error(path, e))?;
58 if bytes_read == 0 {
59 break;
60 }
61
62 let data = &buffer[..bytes_read].to_vec();
63 let hash = self.hash(data, BINARY_HASH_SIZE);
64 self.save_chunk(&hash, data.to_vec())?;
65 hashes.push(hash);
66 }
67
68 Ok(hashes)
69 }
70
71 async fn hashify_text(&mut self, path: &str) -> Result<Vec<String>> {
72 let file = File::open(self.full_path(path))
73 .await
74 .map_err(|e| SyncError::from_io_error(path, e))?;
75 let mut reader = BufReader::new(file);
76 let mut buffer = Vec::new();
77 let mut hashes = Vec::new();
78
79 while reader
80 .read_until(b'\n', &mut buffer)
81 .await
82 .map_err(|e| SyncError::from_io_error(path, e))?
83 > 0
84 {
85 let data: Vec<u8> = buffer.clone();
86 let hash = self.hash(&data, TEXT_HASH_SIZE);
87 self.save_chunk(&hash, data)?;
88 hashes.push(hash);
89
90 buffer.clear();
92 }
93
94 Ok(hashes)
95 }
96
97 pub fn hash(&self, data: &Vec<u8>, size: usize) -> String {
98 let mut hasher = Sha256::new();
99
100 hasher.update(data);
101
102 let result = hasher.finalize();
103 let hex_string = format!("{:x}", result);
104
105 hex_string[0..size].to_string()
106 }
107
108 pub fn exists(&mut self, path: &str) -> bool {
109 let full_path = self.full_path(path);
110
111 full_path.exists()
112 }
113
114 pub async fn save(&mut self, path: &str, hashes: Vec<&str>) -> Result<()> {
116 trace!("saving {:?}", path);
117 let full_path = self.full_path(path);
118
119 if let Some(parent) = full_path.parent() {
120 create_dir_all(parent)
121 .await
122 .map_err(|e| SyncError::from_io_error(path, e))?;
123 }
124
125 let file = File::create(full_path)
126 .await
127 .map_err(|e| SyncError::from_io_error(path, e))?;
128 let mut writer = BufWriter::new(file);
129
130 for hash in hashes {
131 let chunk = self.cache.get(hash)?;
132
133 writer
134 .write_all(&chunk)
135 .await
136 .map_err(|e| SyncError::from_io_error(path, e))?;
137 }
138
139 writer
140 .flush()
141 .await
142 .map_err(|e| SyncError::from_io_error(path, e))?;
143
144 Ok(())
145 }
146
147 pub async fn delete(&mut self, path: &str) -> Result<()> {
148 trace!("deleting {:?}", path);
149 let full_path = self.full_path(path);
150
151 fs::remove_file(full_path)
153 .await
154 .map_err(|e| SyncError::from_io_error(path, e))?;
155
156 Ok(())
157 }
158
159 pub fn read_chunk(&self, chunk_hash: &str) -> Result<Vec<u8>> {
160 self.cache.get(chunk_hash)
161 }
162
163 pub fn save_chunk(&mut self, chunk_hash: &str, content: Vec<u8>) -> Result<()> {
164 self.cache.set(chunk_hash, content)
165 }
166
167 pub fn check_chunk(&self, chunk_hash: &str) -> bool {
168 if chunk_hash.is_empty() {
169 true
170 } else {
171 self.cache.contains(chunk_hash)
172 }
173 }
174}
175
176#[derive(Clone)]
177pub struct BytesWeighter;
178
179impl Weighter<String, Vec<u8>> for BytesWeighter {
180 fn weight(&self, _key: &String, val: &Vec<u8>) -> u32 {
181 val.len().clamp(1, u32::MAX as usize) as u32
183 }
184}
185
186pub struct InMemoryCache {
187 cache: Cache<String, Vec<u8>, BytesWeighter>,
188}
189
190impl InMemoryCache {
191 pub fn new(total_keys: usize, total_weight: u64) -> InMemoryCache {
192 InMemoryCache {
193 cache: Cache::with_weighter(total_keys, total_weight, BytesWeighter),
194 }
195 }
196
197 fn get(&self, chunk_hash: &str) -> Result<Vec<u8>> {
198 if chunk_hash.is_empty() {
199 return Ok(vec![]);
200 }
201
202 match self.cache.get(chunk_hash) {
203 Some(content) => Ok(content.clone()),
204 None => Err(SyncError::GetFromCacheError),
205 }
206 }
207
208 fn set(&mut self, chunk_hash: &str, content: Vec<u8>) -> Result<()> {
209 self.cache.insert(chunk_hash.to_string(), content);
211 Ok(())
212 }
213
214 fn contains(&self, chunk_hash: &str) -> bool {
215 match self.cache.get(chunk_hash) {
216 Some(_content) => true,
217 None => false,
218 }
219 }
220}
221
222pub fn is_binary(p: &Path) -> bool {
223 if let Some(ext) = p.extension() {
224 let ext = ext.to_ascii_lowercase();
225
226 ext == "jpg" || ext == "jpeg" || ext == "png"
227 } else {
228 false
229 }
230}
231
232pub fn is_text(p: &Path) -> bool {
233 if let Some(ext) = p.extension() {
234 let ext = ext.to_ascii_lowercase();
235
236 ext == "cook"
237 || ext == "conf"
238 || ext == "yaml"
239 || ext == "yml"
240 || ext == "md"
241 || ext == "cplan"
242 } else {
243 false
244 }
245}