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
//! 二进制数据
use std::borrow::{BorrowMut, Cow};
use std::fmt::{Debug, Formatter};
use std::fs::File;
use std::io::{ErrorKind, Read, Seek, SeekFrom, Write};
use std::ops::Range;
use std::pin::Pin;
use std::task::{Context, Poll};

use futures_util::Stream;

use crate::tina::data::AppResult;
use crate::{app_debug, app_error_from, app_error_from_none_static, app_system_error};
use bytes::{Bytes, BytesMut};
use futures::{AsyncRead, AsyncSeek};
use httpdate::HttpDate;
use mime::Mime;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::SystemTime;
use tokio::io::ReadBuf;
use tracing::error;

/// 二进制内容
pub trait BinaryContent:
    Debug + Unpin + Stream<Item = AppResult<DataContent>> + AsyncRead + tokio::io::AsyncRead + AsyncSeek + Read + Seek + Send + Sync + 'static
{
    /// 获取大小
    fn get_size(&self) -> Option<u64>;
    /// 是否可用
    fn is_valid(&self) -> bool;
    /// 最新修改时间
    fn last_modified(&self) -> HttpDate;
}

/// 内容枚举
pub enum DataContent {
    /// 静态数据
    STATIC(&'static [u8]),
    /// 动态二进制Bytes
    BYTES(Bytes),
    /// 动态二进制
    VEC(Vec<u8>),
}

impl Debug for DataContent {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            DataContent::STATIC(v) => f.write_fmt(format_args!("[{} content, len: {}]", "STATIC", v.len())),
            DataContent::BYTES(v) => f.write_fmt(format_args!("[{} content, len: {}]", "BYTES", v.len())),
            DataContent::VEC(v) => f.write_fmt(format_args!("[{} content, len: {}]", "VEC", v.len())),
        }
    }
}

impl DataContent {
    /// 从静态数据构建
    pub fn from_static(buf: &'static [u8]) -> DataContent {
        DataContent::STATIC(buf)
    }
    /// 从Bytes构建
    pub fn from_bytes(bytes: Bytes) -> DataContent {
        DataContent::BYTES(bytes)
    }
    /// 从Vec<u8>构建
    pub fn from_vec(vec: Vec<u8>) -> DataContent {
        DataContent::VEC(vec)
    }
    /// 获取大小
    pub fn len(&self) -> usize {
        match self {
            DataContent::STATIC(v) => v.len(),
            DataContent::BYTES(v) => v.len(),
            DataContent::VEC(v) => v.len(),
        }
    }
    /// 是否为空
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// 获取子数据
    pub fn get(&self, range: Range<usize>) -> Option<&[u8]> {
        match self {
            DataContent::STATIC(v) => get_slice(v, range),
            DataContent::BYTES(v) => get_slice(v, range),
            DataContent::VEC(v) => get_slice(v.as_slice(), range),
        }
    }
}

fn get_slice(source: &[u8], range: Range<usize>) -> Option<&[u8]> {
    let mut start = range.start;
    let mut end = range.end;
    let len = source.len();
    if start > len {
        start = len;
    }
    if end > len {
        end = len;
    }
    source.get(start..end)
}

impl Clone for DataContent {
    fn clone(&self) -> Self {
        match self {
            DataContent::STATIC(v) => DataContent::STATIC(v),
            DataContent::BYTES(v) => DataContent::BYTES(v.clone()),
            DataContent::VEC(v) => DataContent::VEC(v.clone()),
        }
    }
}

impl From<DataContent> for Bytes {
    fn from(value: DataContent) -> Self {
        match value {
            DataContent::STATIC(v) => Bytes::from(v),
            DataContent::BYTES(v) => v,
            DataContent::VEC(v) => Bytes::from(v),
        }
    }
}

/// 本地存储文件数据
#[derive(Debug)]
pub struct StoredFileData {
    /// 文件存储路径
    pub store_path: Arc<String>,
    read_handle: Option<File>,
    chunk_size: usize,
    delete_on_drop: bool,
    write_handle: Option<File>,
    copy_lock: Arc<Mutex<()>>,
}

impl StoredFileData {
    /// 构建文件数据
    pub fn new<P: AsRef<Path>>(path: P, delete_on_drop: bool) -> StoredFileData {
        StoredFileData {
            store_path: Arc::new(path.as_ref().to_string_lossy().to_string()),
            read_handle: None,
            chunk_size: 8192,
            delete_on_drop,
            write_handle: None,
            copy_lock: Arc::new(Mutex::new(())),
        }
    }
    /// 获取content-type
    pub fn get_content_type(&self) -> Mime {
        crate::new_mime_guess::from_path(self.store_path.as_str()).first_or(mime::APPLICATION_OCTET_STREAM)
    }
    /// 获取文件名
    pub fn get_file_name(&self) -> Cow<str> {
        Path::new(self.store_path.as_str()).file_name().map(|v| v.to_string_lossy()).unwrap_or_default()
    }
    /// 写入内容
    pub fn write_bytes(&mut self, buf: &[u8]) -> AppResult<()> {
        let path = self.store_path.as_str();
        if self.write_handle.is_none() {
            let file = File::create(path).map_err(|v| app_system_error!("创建文件失败: {}, reason: {:?}", path, v))?;
            self.write_handle = Some(file);
        }
        if let Some(handle) = self.write_handle.as_mut() {
            handle.write_all(buf).map_err(|v| app_system_error!("写入文件内容失败: {}, reason: {:?}", path, v))?;
        }
        Ok(())
    }
    /// 写入一行
    pub fn write_line(&mut self, line: impl AsRef<str>) -> AppResult<()> {
        let line = line.as_ref();
        self.write_bytes(line.as_bytes())?;
        self.write_bytes(b"\r\n")
    }
    /// 刷新文件内容至磁盘
    pub fn flush(&mut self) -> AppResult<()> {
        if let Some(handle) = self.write_handle.as_mut() {
            handle.flush().map_err(|v| app_system_error!("刷新文件内容至磁盘失败: {}, reason: {:?}", self.store_path.as_str(), v))?;
        }
        Ok(())
    }
}

/// 内存数据
#[derive(Debug)]
pub struct MemoryData {
    /// 内容
    pub content: DataContent,
    eof: Arc<Mutex<bool>>,
    read_idx: usize,
}

impl MemoryData {
    /// 构建内存数据
    pub fn new(content: DataContent) -> MemoryData {
        MemoryData {
            content,
            eof: Arc::new(Mutex::new(false)),
            read_idx: 0,
        }
    }
}

impl Clone for MemoryData {
    fn clone(&self) -> Self {
        Self {
            content: self.content.clone(),
            eof: Arc::new(Mutex::new(false)),
            read_idx: 0,
        }
    }
}

impl Read for MemoryData {
    fn read(&mut self, mut buf: &mut [u8]) -> std::io::Result<usize> {
        let range = self.read_idx..self.read_idx + buf.len();
        if let Some(inner) = self.content.get(range) {
            buf.write_all(inner)?;
            let len = inner.len();
            self.read_idx += len;
            return Ok(len);
        }
        Ok(0)
    }
}

impl AsyncRead for MemoryData {
    fn poll_read(self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<std::io::Result<usize>> {
        match Read::read(self.get_mut(), buf) {
            Ok(len) => Poll::Ready(Ok(len)),
            Err(err) => Poll::Ready(Err(err)),
        }
    }
}

impl tokio::io::AsyncRead for MemoryData {
    fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
        match AsyncRead::poll_read(self, cx, buf.initialized_mut()) {
            Poll::Ready(r) => match r {
                Ok(len) => {
                    buf.set_filled(len);
                    Poll::Ready(Ok(()))
                }
                Err(err) => Poll::Ready(Err(err)),
            },
            Poll::Pending => Poll::Pending,
        }
    }
}

impl Seek for MemoryData {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        let new_pos = match pos {
            SeekFrom::Start(v) => v as usize,
            SeekFrom::End(v) => {
                let mut idx = self.content.len() as u64;
                idx = idx.wrapping_add(v as u64);
                idx as usize
            }
            SeekFrom::Current(v) => {
                let mut idx = self.read_idx as u64;
                idx = idx.wrapping_add(v as u64);
                idx as usize
            }
        };
        match new_pos > self.content.len() {
            true => Err(std::io::Error::new(
                ErrorKind::UnexpectedEof,
                app_system_error!("pos is greater than len: {}, {}", new_pos, self.content.len()),
            )),
            false => {
                self.read_idx = new_pos;
                Ok(self.read_idx as u64)
            }
        }
    }
}

impl AsyncSeek for MemoryData {
    fn poll_seek(self: Pin<&mut Self>, _cx: &mut Context<'_>, pos: SeekFrom) -> Poll<std::io::Result<u64>> {
        match Seek::seek(self.get_mut(), pos) {
            Ok(len) => Poll::Ready(Ok(len)),
            Err(err) => Poll::Ready(Err(std::io::Error::new(ErrorKind::Other, err))),
        }
    }
}

impl Read for StoredFileData {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.read_handle.is_none() {
            match File::open(self.store_path.as_str()) {
                Ok(file) => {
                    self.read_handle = Some(file);
                }
                Err(err) => return Err(std::io::Error::new(ErrorKind::Other, err)),
            }
        }
        match self.read_handle.as_mut() {
            None => Ok(0),
            Some(file) => file.read(buf),
        }
    }
}

impl AsyncRead for StoredFileData {
    fn poll_read(self: Pin<&mut Self>, _cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<std::io::Result<usize>> {
        match Read::read(self.get_mut(), buf) {
            Ok(len) => Poll::Ready(Ok(len)),
            Err(err) => Poll::Ready(Err(err)),
        }
    }
}

impl tokio::io::AsyncRead for StoredFileData {
    fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<std::io::Result<()>> {
        match AsyncRead::poll_read(self, cx, buf.initialized_mut()) {
            Poll::Ready(r) => match r {
                Ok(len) => {
                    buf.set_filled(len);
                    Poll::Ready(Ok(()))
                }
                Err(err) => Poll::Ready(Err(err)),
            },
            Poll::Pending => Poll::Pending,
        }
    }
}

impl Seek for StoredFileData {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        if self.read_handle.is_none() {
            match File::open(self.store_path.as_str()) {
                Ok(file) => {
                    self.read_handle = Some(file);
                }
                Err(err) => return Err(std::io::Error::new(ErrorKind::Other, err)),
            }
        }
        match self.read_handle.as_mut() {
            None => Err(std::io::Error::new(ErrorKind::Other, app_system_error!("no file to read"))),
            Some(file) => file.seek(pos),
        }
    }
}

impl AsyncSeek for StoredFileData {
    fn poll_seek(self: Pin<&mut Self>, _cx: &mut Context<'_>, pos: SeekFrom) -> Poll<std::io::Result<u64>> {
        match Seek::seek(self.get_mut(), pos) {
            Ok(len) => Poll::Ready(Ok(len)),
            Err(err) => Poll::Ready(Err(std::io::Error::new(ErrorKind::Other, err))),
        }
    }
}

impl Stream for MemoryData {
    type Item = AppResult<DataContent>;

    fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let lock = self.eof.lock().map_err(app_error_from_none_static!());
        match lock {
            Ok(mut lock) => match *lock {
                true => Poll::Ready(None),
                false => {
                    let p = Poll::Ready(Some(Ok(self.content.clone())));
                    (*lock) = true;
                    p
                }
            },
            Err(err) => Poll::Ready(Some(Err(err))),
        }
    }
}

impl BinaryContent for MemoryData {
    fn get_size(&self) -> Option<u64> {
        match self.content {
            DataContent::STATIC(v) => Some(v.len() as u64),
            DataContent::BYTES(ref v) => Some(v.len() as u64),
            DataContent::VEC(ref v) => Some(v.len() as u64),
        }
    }

    fn is_valid(&self) -> bool {
        true
    }

    fn last_modified(&self) -> HttpDate {
        HttpDate::from(SystemTime::now())
    }
}

impl BinaryContent for StoredFileData {
    fn get_size(&self) -> Option<u64> {
        match File::open(self.store_path.as_str()) {
            Ok(f) => match f.metadata() {
                Ok(m) => Some(m.len()),
                Err(_) => None,
            },
            Err(_) => None,
        }
    }

    fn is_valid(&self) -> bool {
        Path::new(self.store_path.as_str()).exists()
    }

    fn last_modified(&self) -> HttpDate {
        match File::open(self.store_path.as_str()) {
            Ok(f) => match f.metadata() {
                Ok(m) => match m.modified() {
                    Ok(v) => HttpDate::from(v),
                    Err(_) => HttpDate::from(SystemTime::now()),
                },
                Err(_) => HttpDate::from(SystemTime::now()),
            },
            Err(_) => HttpDate::from(SystemTime::now()),
        }
    }
}

impl Clone for StoredFileData {
    fn clone(&self) -> Self {
        let _lock = self.copy_lock.lock();
        Self {
            store_path: Arc::clone(&self.store_path),
            read_handle: None,
            chunk_size: self.chunk_size,
            delete_on_drop: self.delete_on_drop,
            write_handle: None,
            copy_lock: Arc::clone(&self.copy_lock),
        }
    }
}

impl Stream for StoredFileData {
    type Item = AppResult<DataContent>;

    fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if let Some(handle) = self.write_handle.as_mut() {
            match handle.flush() {
                Ok(_) => {
                    self.write_handle = None;
                }
                Err(err) => {
                    error!("刷新文件内容至磁盘失败: {}, reason: {:?}", self.store_path.as_str(), err);
                    return Poll::Ready(Some(Err(app_error_from!(err))));
                }
            }
        }
        if self.read_handle.is_none() {
            match File::open(self.store_path.as_str()) {
                Ok(file) => {
                    self.read_handle = Some(file);
                }
                Err(err) => return Poll::Ready(Some(Err(crate::app_system_error!("{:?}", err)))),
            }
        }
        let chunk_size = self.chunk_size;
        if let Some(file) = self.read_handle.borrow_mut() {
            let mut buf = BytesMut::with_capacity(chunk_size);
            buf.resize(chunk_size, 0);
            return match file.read(buf.as_mut()) {
                Ok(len) => {
                    if len == 0 {
                        return Poll::Ready(None);
                    }
                    buf.resize(len, 0);
                    Poll::Ready(Some(Ok(DataContent::BYTES(buf.freeze()))))
                }
                Err(err) => Poll::Ready(Some(Err(crate::app_system_error!("{:?}", err)))),
            };
        }
        Poll::Pending
    }
}

impl Drop for StoredFileData {
    fn drop(&mut self) {
        if !self.delete_on_drop {
            return;
        }
        let _lock = self.copy_lock.lock();
        if Arc::strong_count(&self.store_path) <= 1 && Path::new(self.store_path.as_str()).exists() {
            match std::fs::remove_file(self.store_path.as_str()) {
                Ok(_) => {
                    app_debug!("删除文件: {}", self.store_path)
                }
                Err(err) => {
                    tracing::error!("删除文件失败: {}, reason: {:?}", self.store_path.as_str(), err);
                }
            }
        }
    }
}