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
use log::*;
use std::{
    sync::{Arc},
    path::{Path, PathBuf},
};
use async_std::{
    prelude::*, 
    fs::{self, OpenOptions},  
};
use cyfs_base::*;

use crate::{
    ndn::*
};


struct WriterImpl {
    path: PathBuf,
    tmp_path: Option<PathBuf>,
    chunk: ChunkId,
}

#[derive(Clone)]
pub struct LocalChunkWriter(Arc<WriterImpl>);

impl std::fmt::Display for LocalChunkWriter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "LocalChunkWriter{{path:{:?}}}", self.path())
    }
}


impl LocalChunkWriter {
    pub fn from_path(
        path: &Path,
        chunk: &ChunkId,
    ) -> Self {
        let tmp_path = format!(
            "{}-{}",
            path.file_name().unwrap().to_str().unwrap(),
            bucky_time_now()
        );
        Self::new(
            path.to_owned(),
            Some(path.parent().unwrap().join(tmp_path.as_str())),
            chunk,
        )
    }


    pub fn new(
        path: PathBuf,
        tmp_path: Option<PathBuf>,
        chunk: &ChunkId,
    ) -> Self {
        Self(Arc::new(WriterImpl {
            path,
            tmp_path,
            chunk: chunk.clone(),
        }))
    }

    
    fn path(&self) -> &Path {
        self.0.path.as_path()
    }

    fn chunk(&self) -> &ChunkId {
        &self.0.chunk
    }


    async fn write_inner<R: async_std::io::Read + Unpin>(&self, reader: R) -> BuckyResult<()> {
        if self.chunk().len() == 0 {
            return Ok(());
        }

        let path = self.0.tmp_path.as_ref().map(|p| p.as_path()).unwrap_or(self.path());

        let file = OpenOptions::new().create(true).write(true).open(path).await
            .map_err(|e| {
                let msg = format!("{} open file failed for {}", self, e);
                error!("{}", msg);
                BuckyError::new(BuckyErrorCode::IoError, msg)
            })?;

        let _ = async_std::io::copy(reader, file).await
            .map_err(|e| {
                let msg = format!(
                    "{} write chunk file failed for {}",
                    self, 
                    e
                );
                error!("{}", msg);

                BuckyError::new(BuckyErrorCode::IoError, msg)
            })?;
        
            
        if self.0.tmp_path.is_some() {
            let tmp_path = self.0.tmp_path.as_ref().unwrap().as_path();
            let ret = fs::rename(tmp_path, self.path()).await;
            if ret.is_err() {
                if !self.path().exists() {
                    let msg = format!("{} rename tmp file failed for {}", self, ret.err().unwrap());
                    error!("{}", msg);

                    return Err(BuckyError::new(BuckyErrorCode::IoError, msg));
                }
            }
        }

        info!("{} writen chunk to file", self);

        Ok(())
    }

    pub async fn write<R: async_std::io::Read + Unpin>(&self, reader: R) -> BuckyResult<()> {
        if self.chunk().len() == 0 {
            return Ok(());
        }

        let ret = self.write_inner(reader).await;

        if self.0.tmp_path.is_some() {
            let tmp_path = self.0.tmp_path.as_ref().unwrap().as_path();
            let _ = fs::remove_file(tmp_path).await;
        }
        
        ret
    }
}


struct ListWriterImpl {
    path: PathBuf,
    desc: ChunkListDesc,
}

#[derive(Clone)]
pub struct LocalChunkListWriter(Arc<ListWriterImpl>);

impl std::fmt::Display for LocalChunkListWriter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "LocalChunkListWriter{{path:{:?}}}", self.path())
    }
}

impl LocalChunkListWriter {
    pub fn from_file(
        path: PathBuf, 
        file: &File
    ) -> BuckyResult<Self> {
        Ok(Self::new(path, &ChunkListDesc::from_file(&file)?))
    }

    pub fn new(
        path: PathBuf, 
        desc: &ChunkListDesc
    ) -> Self {
        
        Self(Arc::new(ListWriterImpl {
            path, 
            desc: desc.clone(),  
        }))
    }


    fn path(&self) -> &Path {
        self.0.path.as_path()
    }

    fn chunk_list(&self) -> &ChunkListDesc {
        &self.0.desc
    }

    pub async fn write<R: async_std::io::Read + Unpin>(&self, reader: R) -> BuckyResult<()> {
        // 零长度的chunk不需要触发真正的写入操作
        if self.chunk_list().total_len() == 0 {
            return Ok(());
        }

        let mut reader = reader;
        let mut file = OpenOptions::new()
            .create(true)
            .write(true)
            .open(self.path())
            .await
            .map_err(|e| {
                let msg = format!("{} open file failed for {}", self, e);
                error!("{}", msg);
                BuckyError::new(BuckyErrorCode::IoError, msg)
            })?;

        // 强制设置为目标大小
        file.set_len(self.chunk_list().total_len())
            .await
            .map_err(|e| {
                let msg = format!(
                    "{} create trans data file with len {} failed for {}",
                    self,
                    self.chunk_list().total_len(),
                    e
                );
                error!("{}", msg);

                BuckyError::new(BuckyErrorCode::IoError, msg)
            })?;

        // 强制设置为目标大小
        file.set_len(self.chunk_list().total_len()).await.map_err(|e| {
            let msg = format!(
                "{} create trans data file with len {} failed for {}",
                self, 
                self.chunk_list().total_len(),
                e
            );
            error!("{}", msg);

            BuckyError::new(BuckyErrorCode::IoError, msg)
        })?;

        for chunk in self.chunk_list().chunks().iter() {
            if chunk.len() == 0 {
                continue;
            }

            let mut buffer = vec![0u8; chunk.len()];
            reader.read_exact(&mut buffer[..]).await?;

            file.write_all(&buffer[..]).await?;
        }

        Ok(())
    }
}



pub fn local_chunk_writer(
    chunk: &ChunkId, 
    path: PathBuf
) -> LocalChunkWriter {
    LocalChunkWriter::new(path, None, chunk)
}

pub fn local_file_writer(
    file: &File, 
    path: PathBuf 
) -> BuckyResult<LocalChunkListWriter> {
    Ok(LocalChunkListWriter::new(path, &ChunkListDesc::from_file(&file)?))
}