fastdfs 0.1.0

Rust client for FastDFS distributed file system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use super::storage_client::{StorageClient, StorageClientFactor};
use super::tracker_client::{TrackerClient, TrackerClientFactor};
use crate::pool::{KeyedObjectPool, PoolConfig, PooledObject};
use crate::types::{FileInfo, GroupStat, Metadata, MetadataFlag, StorageServer, StorageStat};
use crate::types::{FDFS_QUERY_FINFO_FLAGS_KEEP_SILENCE, FDFS_QUERY_FINFO_FLAGS_NOT_CALC_CRC32};
use crate::{ClientOptions, FileId};
use crate::{FastDFSError, Result};
use bytes::Bytes;
use std::net::SocketAddr;
use std::ops::Deref;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite};

pub struct ClientInner {
    config: ClientOptions,
    tracker_pool: KeyedObjectPool<SocketAddr, TrackerClient, TrackerClientFactor>,
    storage_pool: KeyedObjectPool<SocketAddr, StorageClient, StorageClientFactor>,
    closed: AtomicBool,
}

type TrackerClientPooled = PooledObject<SocketAddr, TrackerClient, TrackerClientFactor>;
type StorageClientPooled = PooledObject<SocketAddr, StorageClient, StorageClientFactor>;

impl ClientInner {
    async fn get_tracker_client(&self) -> Result<TrackerClientPooled> {
        {
            if self.closed.load(Ordering::Relaxed) {
                return Err(FastDFSError::ClientClosed);
            }
        }
        for addr in &self.config.tracker_addrs {
            let addr: SocketAddr = addr.parse().map_err(|_| {
                FastDFSError::InvalidArgument(format!("Invalid tracker address: {}", addr))
            })?;

            if let Ok(mut client) = self.tracker_pool.get(&addr).await {
                client.in_use();
                return Ok(client);
            }
        }

        Err(FastDFSError::TrackerServerOffline(
            self.config.tracker_addrs.join(", "),
        ))
    }

    async fn get_storage_client(&self, server_info: StorageServer) -> Result<StorageClientPooled> {
        {
            if self.closed.load(Ordering::Relaxed) {
                return Err(FastDFSError::ClientClosed);
            }
        }
        let addr = format!("{}:{}", server_info.ip_addr, server_info.port);
        let addr: SocketAddr = addr.parse().map_err(|_| {
            FastDFSError::InvalidArgument(format!("Invalid tracker address: {}", addr))
        })?;

        let mut result = self.storage_pool.get(&addr).await?;
        result.store_path_index(server_info.store_path_index);
        result.in_use();
        Ok(result)
    }
}

// Tracker Service
impl ClientInner {
    /// query group stat info
    pub async fn list_groups(&self) -> Result<Vec<GroupStat>> {
        let mut tc = self.get_tracker_client().await?;
        tc.list_groups().await
    }

    /// query storage server stat info of the group
    pub async fn list_storages<S0: AsRef<str>, S1: AsRef<str>>(
        &self,
        group: S0,
        server_id: Option<S1>,
    ) -> Result<Vec<StorageStat>> {
        let mut tc = self.get_tracker_client().await?;
        tc.list_storages(group, server_id).await
    }

    /// delete a storage server from the tracker server
    pub async fn delete_storage<S0: AsRef<str>, S1: AsRef<str>>(
        &self,
        group: S0,
        server_id: S1,
    ) -> Result<bool> {
        let addr = server_id.as_ref();
        let addr: SocketAddr = addr.parse().map_err(|_| {
            FastDFSError::InvalidArgument(format!("Invalid tracker address: {}", addr))
        })?;
        let mut tc = self.get_tracker_client().await?;
        let result = tc.delete_storage(group, server_id).await?;
        if result {
            self.storage_pool.remove_key(&addr).await;
        }
        Ok(result)
    }
}

// Storage Service
impl ClientInner {
    /// Uploads data from a stream
    pub async fn upload_file<R: AsyncRead + Unpin + ?Sized>(
        &self,
        stream: &mut R,
        stream_size: u64,
        file_ext_name: &str,
        metadata: Option<&Metadata>,
        is_appender: bool,
    ) -> Result<FileId> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_store_storage::<&str>(None).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.upload_file(stream, stream_size, file_ext_name, metadata, is_appender)
            .await
    }

    /// Uploads data from a buffer
    pub async fn upload_file_buf(
        &self,
        data: &[u8],
        file_ext_name: &str,
        metadata: Option<&Metadata>,
        is_appender: bool,
    ) -> Result<FileId> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_store_storage::<&str>(None).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.upload_file_buf(data, file_ext_name, metadata, is_appender)
            .await
    }

    /// Uploads a file from the local filesystem
    pub async fn upload_file_local(
        &self,
        local_filename: &str,
        metadata: Option<&Metadata>,
        is_appender: bool,
    ) -> Result<FileId> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_store_storage::<&str>(None).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.upload_file_local(local_filename, metadata, is_appender)
            .await
    }

    /// Downloads a file and copy to a stream
    ///
    /// # Arguments
    ///
    /// * `file_id`: file id
    /// * `writer`:  a stream of the copy target
    /// * `offset`: the start offset of the file
    /// * `length`: download bytes, 0 for remain bytes from offset
    pub async fn download_file<W: AsyncWrite + Unpin + ?Sized>(
        &self,
        file_id: &FileId,
        writer: &mut W,
        offset: u64,
        length: u64,
    ) -> Result<u64> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_fetch_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.download_file(file_id, writer, offset, length).await
    }

    /// download file from storage server
    ///
    /// # Arguments
    ///
    /// * `file_id`: file id
    /// * `offset`: the start offset of the file
    /// * `length`: download bytes, 0 for remain bytes from offset
    pub async fn download_file_buf(
        &self,
        file_id: &FileId,
        offset: u64,
        length: u64,
    ) -> Result<Bytes> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_fetch_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.download_file_buf(file_id, offset, length).await
    }

    /// Downloads a file and saves it to the local filesystem
    pub async fn download_file_local(&self, file_id: &FileId, local_filename: &str) -> Result<u64> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_fetch_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.download_file_local(file_id, local_filename).await
    }

    /// Deletes a file from FastDFS
    pub async fn delete_file(&self, file_id: &FileId) -> Result<()> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_update_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.delete_file(file_id).await
    }

    /// append file to storage server (by stream)
    pub async fn append_file<R: AsyncRead + Unpin + ?Sized>(
        &self,
        file_id: &FileId,
        stream: &mut R,
        stream_size: u64,
    ) -> Result<()> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_update_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.append_file(file_id, stream, stream_size).await
    }

    /// append file to storage server (by file buff)
    pub async fn append_file_buf(&self, file_id: &FileId, data: &[u8]) -> Result<()> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_update_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.append_file_buf(file_id, data).await
    }

    /// append file to storage server (by local filesystem)
    pub async fn append_file_local(&self, file_id: &FileId, local_filename: &str) -> Result<()> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_update_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.append_file_local(file_id, local_filename).await
    }

    /// modify appender file to storage server (by stream)
    /// # Arguments
    ///
    /// * `file_offset`: the offset of appender file
    pub async fn modify_file<R: AsyncRead + Unpin + ?Sized>(
        &self,
        file_id: &FileId,
        file_offset: u64,
        stream: &mut R,
        stream_size: u64,
    ) -> Result<()> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_update_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.modify_file(file_id, file_offset, stream, stream_size)
            .await
    }

    /// modify appender file to storage server (by file buff)
    /// # Arguments
    ///
    /// * `file_offset`: the offset of appender file
    pub async fn modify_file_buf(
        &self,
        file_id: &FileId,
        file_offset: u64,
        data: &[u8],
    ) -> Result<()> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_update_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.modify_file_buf(file_id, file_offset, data).await
    }

    /// modify appender file to storage server (by local filesystem)
    /// # Arguments
    ///
    /// * `file_offset`: the offset of appender file
    pub async fn modify_file_local(
        &self,
        file_id: &FileId,
        file_offset: u64,
        local_filename: &str,
    ) -> Result<()> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_update_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.modify_file_local(file_id, file_offset, local_filename)
            .await
    }

    /// truncate appender file from storage server
    ///
    /// # Arguments
    ///
    /// * `file_id`: the file id of appender file
    /// * `truncated_file_size`: truncated file size
    pub async fn truncate_file(&self, file_id: &FileId, truncated_file_size: u64) -> Result<()> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_update_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.truncate_file(file_id, truncated_file_size).await
    }

    /// truncate appender file to size 0 from storage server
    ///
    /// # Arguments
    ///
    /// * `file_id`: the file id of appender file
    pub async fn truncate_file0(&self, file_id: &FileId) -> Result<()> {
        self.truncate_file(&file_id, 0).await
    }

    /// regenerate filename for appender file, since `v6.02`
    ///
    /// # Arguments
    ///
    /// * `file_id`: the file id of appender file
    pub async fn regenerate_appender_filename(&self, file_id: &FileId) -> Result<FileId> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_update_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.regenerate_appender_filename(file_id).await
    }

    pub async fn set_metadata(
        &self,
        file_id: &FileId,
        metadata: &Metadata,
        flag: MetadataFlag,
    ) -> Result<()> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_update_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.set_metadata(file_id, metadata, flag).await
    }

    pub async fn get_metadata(&self, file_id: &FileId) -> Result<Metadata> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_fetch_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.get_metadata(file_id).await
    }

    /// query file info
    pub async fn get_file_info(&self, file_id: &FileId) -> Result<FileInfo> {
        self.get_file_info_with_flag(file_id, 0).await
    }

    /// query file info
    ///
    /// # Arguments
    ///
    /// * `file_id`: file id
    /// * `flag`: since `v6.15.1` , combined flags as following:
    ///     - `FDFS_QUERY_FINFO_FLAGS_NOT_CALC_CRC32` : do NOT calculate CRC32 for appender file or slave file
    ///     - `FDFS_QUERY_FINFO_FLAGS_KEEP_SILENCE`   : keep silence, when this file not exist, do not log error on storage server
    pub async fn get_file_info_with_flag(&self, file_id: &FileId, flag: u8) -> Result<FileInfo> {
        let mut tc = self.get_tracker_client().await?;
        let server_info = tc.get_fetch_storage(file_id).await?;
        let mut sc = self.get_storage_client(server_info).await?;
        sc.get_file_info_with_flag(file_id, flag).await
    }
}

// ext
impl ClientInner {
    /// Checks if a file exists on the storage server
    pub async fn file_exists(&self, file_id: &FileId) -> Result<bool> {
        let flag = FDFS_QUERY_FINFO_FLAGS_NOT_CALC_CRC32 | FDFS_QUERY_FINFO_FLAGS_KEEP_SILENCE;
        let result = self.get_file_info_with_flag(file_id, flag).await;
        match result {
            Ok(_) => Ok(true),
            Err(FastDFSError::FileNotFound(_)) => Ok(false),
            Err(FastDFSError::InvalidArgument(_)) => Ok(false),
            Err(e) => Err(e),
        }
    }

    /// Closes the client and releases all resources
    ///
    /// After calling close, all operations will return ClientClosed error.
    /// It's safe to call close multiple times.
    pub async fn close(&self) {
        self.closed.store(true, Ordering::Relaxed);
        self.tracker_pool.remove_all().await;
        self.storage_pool.remove_all().await;
    }
}

#[derive(Clone)]
pub struct FdfsClient {
    inner: Arc<ClientInner>,
}

/// Validates the client configuration
fn validate_config(config: &ClientOptions) -> Result<()> {
    if config.tracker_addrs.is_empty() {
        return Err(FastDFSError::InvalidArgument(
            "Tracker addresses are required".to_string(),
        ));
    }

    for addr in &config.tracker_addrs {
        if addr.is_empty() || !addr.contains(':') {
            return Err(FastDFSError::InvalidArgument(format!(
                "Invalid tracker address: {}",
                addr
            )));
        }
    }

    Ok(())
}

fn pool_config(config: &ClientOptions) -> PoolConfig {
    PoolConfig {
        max_total_per_key: config.max_connections,
        test_on_borrow: false,
        test_on_return: false,
        ..PoolConfig::default()
    }
}

impl FdfsClient {
    pub fn new(config: ClientOptions) -> Result<Self> {
        validate_config(&config)?;

        let tracker_factor = TrackerClientFactor {
            version: config.version,
            connect_timeout: config.connect_timeout,
        };
        let storage_factor = StorageClientFactor {
            version: config.version,
            connect_timeout: config.connect_timeout,
        };
        let pool_config = pool_config(&config);

        let client = ClientInner {
            config,
            tracker_pool: KeyedObjectPool::new(tracker_factor, Some(pool_config)),
            storage_pool: KeyedObjectPool::new(storage_factor, Some(pool_config)),
            closed: AtomicBool::new(false),
        };

        Ok(Self {
            inner: Arc::new(client),
        })
    }
}

impl Deref for FdfsClient {
    type Target = ClientInner;
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}