cyfs-lib 0.8.3

Rust cyfs-lib package
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
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
use super::output_request::*;
use crate::base::*;
use crate::*;
use cyfs_base::*;
use cyfs_core::TransContextObject;

use http_types::{Method, Request, Url};
use std::sync::Arc;

#[derive(Clone)]
pub struct TransRequestor {
    dec_id: Option<SharedObjectStackDecID>,
    requestor: HttpRequestorRef,
    service_url: Url,
}

impl TransRequestor {
    pub fn new(dec_id: Option<SharedObjectStackDecID>, requestor: HttpRequestorRef) -> Self {
        let addr = requestor.remote_addr();

        let url = format!("http://{}/trans/", addr);
        let url = Url::parse(&url).unwrap();

        Self {
            dec_id,
            requestor,
            service_url: url,
        }
    }

    pub fn clone_processor(&self) -> TransOutputProcessorRef {
        Arc::new(self.clone())
    }

    fn encode_common_headers(&self, com_req: &NDNOutputRequestCommon, http_req: &mut Request) {
        if let Some(dec_id) = &com_req.dec_id {
            http_req.insert_header(cyfs_base::CYFS_DEC_ID, dec_id.to_string());
        } else if let Some(dec_id) = &self.dec_id {
            if let Some(dec_id) = dec_id.get() {
                http_req.insert_header(cyfs_base::CYFS_DEC_ID, dec_id.to_string());
            }
        }

        RequestorHelper::encode_opt_header_with_encoding(
            http_req,
            cyfs_base::CYFS_REQ_PATH,
            com_req.req_path.as_deref(),
        );
        http_req.insert_header(CYFS_API_LEVEL, com_req.level.to_string());

        if let Some(target) = &com_req.target {
            http_req.insert_header(cyfs_base::CYFS_TARGET, target.to_string());
        }

        if !com_req.referer_object.is_empty() {
            RequestorHelper::insert_headers_with_encoding(
                http_req,
                cyfs_base::CYFS_REFERER_OBJECT,
                &com_req.referer_object,
            );
        }

        http_req.insert_header(cyfs_base::CYFS_FLAGS, com_req.flags.to_string());
    }

    pub async fn get_context(
        &self,
        req: TransGetContextOutputRequest,
    ) -> BuckyResult<TransGetContextOutputResponse> {
        info!(
            "will get context id={:?}, path={:?}",
            req.context_id, req.context_path
        );

        let url = self.service_url.join("get_context").unwrap();
        let mut http_req = Request::new(Method::Post, url);

        self.encode_common_headers(&req.common, &mut http_req);
        let body = req.encode_string();
        http_req.set_body(body);

        let mut resp = self.requestor.request(http_req).await?;
        match resp.status() {
            code if code.is_success() => {
                let context = RequestorHelper::decode_raw_object_body(&mut resp).await?;

                Ok(TransGetContextOutputResponse { context })
            }
            code @ _ => {
                let e = RequestorHelper::error_from_resp(&mut resp).await;
                error!(
                    "get context failed: id={:?}, path={:?}, status={}, {}",
                    req.context_id, req.context_path, code, e
                );

                Err(e)
            }
        }
    }

    pub async fn put_context(&self, req: TransPutContextOutputRequest) -> BuckyResult<()> {
        info!("will put context {}", req.context.context_path());

        let url = self.service_url.join("put_context").unwrap();
        let mut http_req = Request::new(Method::Post, url);

        self.encode_common_headers(&req.common, &mut http_req);

        if let Some(access) = &req.access {
            http_req.insert_header(cyfs_base::CYFS_ACCESS, access.value().to_string());
        }
        
        let body = req.context.to_vec()?;
        http_req.set_body(body);

        let mut resp = self.requestor.request(http_req).await?;
        match resp.status() {
            code if code.is_success() => Ok(()),
            code @ _ => {
                let e = RequestorHelper::error_from_resp(&mut resp).await;
                error!(
                    "update context failed: context={}, status={}, {}",
                    req.context.context_path(),
                    code,
                    e
                );
                Err(e)
            }
        }
    }

    pub async fn create_task(
        &self,
        req: TransCreateTaskOutputRequest,
    ) -> BuckyResult<TransCreateTaskOutputResponse> {
        info!("will create trans task: {:?}", req);

        let url = self.service_url.join("task").unwrap();
        let mut http_req = Request::new(Method::Post, url);

        self.encode_common_headers(&req.common, &mut http_req);
        let body = req.encode_string();
        http_req.set_body(body);

        let mut resp = self.requestor.request(http_req).await?;

        match resp.status() {
            code if code.is_success() => {
                let body = resp.body_string().await.map_err(|e| {
                    let msg = format!(
                        "trans create task failed, read body string error! req={:?} {}",
                        req, e
                    );
                    error!("{}", msg);

                    BuckyError::from(msg)
                })?;

                let resp = TransCreateTaskOutputResponse::decode_string(&body).map_err(|e| {
                    error!(
                        "decode trans create task resp from body string error: body={} {}",
                        body, e,
                    );
                    e
                })?;

                debug!("trans create task success: resp={:?}", resp.task_id);

                Ok(resp)
            }
            code @ _ => {
                let e = RequestorHelper::error_from_resp(&mut resp).await;
                error!(
                    "create task failed: obj={}, status={}, {}",
                    req.object_id, code, e
                );
                Err(e)
            }
        }
    }

    pub async fn control_task(&self, req: TransControlTaskOutputRequest) -> BuckyResult<()> {
        info!("will control trans task: {:?}", req);

        let url = self.service_url.join("task").unwrap();
        let mut http_req = Request::new(Method::Put, url);

        self.encode_common_headers(&req.common, &mut http_req);
        let body = req.encode_string();
        http_req.set_body(body);

        let mut resp = self.requestor.request(http_req).await?;

        match resp.status() {
            code if code.is_success() => Ok(()),
            code @ _ => {
                let e = RequestorHelper::error_from_resp(&mut resp).await;
                error!(
                    "stop trans task failed: task={}, status={}, {}",
                    req.task_id, code, e
                );
                Err(e)
            }
        }
    }

    pub async fn start_task(&self, req: TransTaskOutputRequest) -> BuckyResult<()> {
        Self::control_task(
            self,
            TransControlTaskOutputRequest {
                common: req.common.clone(),
                task_id: req.task_id.clone(),
                action: TransTaskControlAction::Start,
            },
        )
        .await
    }

    pub async fn stop_task(&self, req: TransTaskOutputRequest) -> BuckyResult<()> {
        Self::control_task(
            self,
            TransControlTaskOutputRequest {
                common: req.common.clone(),
                task_id: req.task_id.clone(),
                action: TransTaskControlAction::Stop,
            },
        )
        .await
    }

    pub async fn delete_task(&self, req: TransTaskOutputRequest) -> BuckyResult<()> {
        Self::control_task(
            self,
            TransControlTaskOutputRequest {
                common: req.common.clone(),
                task_id: req.task_id.clone(),
                action: TransTaskControlAction::Delete,
            },
        )
        .await
    }

    pub async fn get_task_state(
        &self,
        req: TransGetTaskStateOutputRequest,
    ) -> BuckyResult<TransGetTaskStateOutputResponse> {
        info!("will get trans task state: {:?}", req);

        let url = self.service_url.join("task/state").unwrap();
        let mut http_req = Request::new(Method::Get, url);

        self.encode_common_headers(&req.common, &mut http_req);
        let body = req.encode_string();
        http_req.set_body(body);

        let mut resp = self.requestor.request(http_req).await?;

        match resp.status() {
            code if code.is_success() => {
                let content = resp.body_json().await.map_err(|e| {
                    let msg = format!("parse TransTaskState resp body error! err={}", e);
                    error!("{}", msg);
                    BuckyError::new(BuckyErrorCode::InvalidData, msg)
                })?;

                info!(
                    "got trans task state: task={}, state={:?}",
                    req.task_id, content
                );

                Ok(content)
            }
            code @ _ => {
                let e = RequestorHelper::error_from_resp(&mut resp).await;
                error!(
                    "get trans task state failed: task={}, status={}, {}",
                    req.task_id, code, e,
                );
                Err(e)
            }
        }
    }

    pub async fn query_tasks(
        &self,
        req: TransQueryTasksOutputRequest,
    ) -> BuckyResult<TransQueryTasksOutputResponse> {
        info!("will query tasks: {:?}", req);

        let url = self.service_url.join("tasks").unwrap();
        let mut http_req = Request::new(Method::Post, url);

        self.encode_common_headers(&req.common, &mut http_req);
        let body = req.encode_string();
        http_req.set_body(body);

        let mut resp = self.requestor.request(http_req).await?;

        match resp.status() {
            code if code.is_success() => {
                let content = resp.body_string().await.map_err(|e| {
                    let msg = format!("get query task resp body error! err={}", e);
                    error!("{}", msg);
                    BuckyError::new(BuckyErrorCode::InvalidData, msg)
                })?;

                let resp = TransQueryTasksOutputResponse::decode_string(content.as_str())?;
                Ok(resp)
            }
            code @ _ => {
                let e = RequestorHelper::error_from_resp(&mut resp).await;
                error!("query tasks failed: status={}, msg={}", code, e);

                Err(e)
            }
        }
    }

    pub async fn publish_file(
        &self,
        req: TransPublishFileOutputRequest,
    ) -> BuckyResult<TransPublishFileOutputResponse> {
        info!("will publish file: {:?}", req);

        let url = self.service_url.join("file").unwrap();
        let mut http_req = Request::new(Method::Post, url);

        self.encode_common_headers(&req.common, &mut http_req);
        let body = req.encode_string();
        http_req.set_body(body);

        let mut resp = self.requestor.request(http_req).await?;

        match resp.status() {
            code if code.is_success() => {
                let body = resp.body_string().await.map_err(|e| {
                    let msg = format!(
                        "trans publish file failed, read body string error! req={:?} {}",
                        req, e
                    );
                    error!("{}", msg);

                    BuckyError::from(msg)
                })?;

                let resp = TransPublishFileOutputResponse::decode_string(&body).map_err(|e| {
                    error!(
                        "decode trans publish file resp from body string error: body={} {}",
                        body, e,
                    );
                    e
                })?;

                debug!("trans publish file success: resp={:?}", resp);

                Ok(resp)
            }
            code @ _ => {
                let e = RequestorHelper::error_from_resp(&mut resp).await;
                error!(
                    "trans publish file failed: file={}, status={}, {}",
                    req.local_path.display(),
                    code,
                    e
                );

                Err(e)
            }
        }
    }

    pub async fn get_task_group_state(
        &self,
        req: TransGetTaskGroupStateOutputRequest,
    ) -> BuckyResult<TransGetTaskGroupStateOutputResponse> {
        info!("will get trans task group state: {:?}", req);

        let url = self.service_url.join("task_group/state").unwrap();
        let mut http_req = Request::new(Method::Post, url);

        self.encode_common_headers(&req.common, &mut http_req);
        http_req.set_body(serde_json::to_string(&req).unwrap());

        let mut resp = self.requestor.request(http_req).await?;

        if resp.status().is_success() {
            let content = resp.body_json().await.map_err(|e| {
                let msg = format!("parse get task group state resp body error! err={}", e);
                error!("{}", msg);
                BuckyError::new(BuckyErrorCode::InvalidData, msg)
            })?;

            info!(
                "got trans task group state: task_group={}, state={:?}",
                req.group, content
            );

            Ok(content)
        } else {
            let e = RequestorHelper::error_from_resp(&mut resp).await;
            error!(
                "get trans task state failed: task_group={}, status={}, {}",
                req.group,
                resp.status(),
                e
            );

            Err(e)
        }
    }

    pub async fn control_task_group(
        &self,
        req: TransControlTaskGroupOutputRequest,
    ) -> BuckyResult<TransControlTaskGroupOutputResponse> {
        info!("will control trans task group: {:?}", req);

        let url = self.service_url.join("task_group").unwrap();
        let mut http_req = Request::new(Method::Put, url);

        self.encode_common_headers(&req.common, &mut http_req);
        http_req.set_body(serde_json::to_string(&req).unwrap());

        let mut resp = self.requestor.request(http_req).await?;

        if resp.status().is_success() {
            let resp = resp.body_json().await.map_err(|e| {
                let msg = format!(
                    "trans control task group failed, read body string error! req={:?} {}",
                    req, e
                );
                error!("{}", msg);

                BuckyError::from(msg)
            })?;

            debug!("trans control task group success: resp={:?}", resp);

            Ok(resp)
        } else {
            let e = RequestorHelper::error_from_resp(&mut resp).await;
            error!("trans control task failed! status={}, {}", resp.status(), e);

            Err(e)
        }
    }
}

#[async_trait::async_trait]
impl TransOutputProcessor for TransRequestor {
    async fn get_context(
        &self,
        req: TransGetContextOutputRequest,
    ) -> BuckyResult<TransGetContextOutputResponse> {
        Self::get_context(self, req).await
    }

    async fn put_context(&self, req: TransPutContextOutputRequest) -> BuckyResult<()> {
        Self::put_context(self, req).await
    }

    async fn create_task(
        &self,
        req: TransCreateTaskOutputRequest,
    ) -> BuckyResult<TransCreateTaskOutputResponse> {
        Self::create_task(self, req).await
    }

    async fn query_tasks(
        &self,
        req: TransQueryTasksOutputRequest,
    ) -> BuckyResult<TransQueryTasksOutputResponse> {
        Self::query_tasks(self, req).await
    }

    async fn get_task_state(
        &self,
        req: TransGetTaskStateOutputRequest,
    ) -> BuckyResult<TransGetTaskStateOutputResponse> {
        Self::get_task_state(self, req).await
    }

    async fn publish_file(
        &self,
        req: TransPublishFileOutputRequest,
    ) -> BuckyResult<TransPublishFileOutputResponse> {
        Self::publish_file(self, req).await
    }

    async fn control_task(&self, req: TransControlTaskOutputRequest) -> BuckyResult<()> {
        Self::control_task(self, req).await
    }

    async fn get_task_group_state(
        &self,
        req: TransGetTaskGroupStateOutputRequest,
    ) -> BuckyResult<TransGetTaskGroupStateOutputResponse> {
        Self::get_task_group_state(self, req).await
    }

    async fn control_task_group(
        &self,
        req: TransControlTaskGroupOutputRequest,
    ) -> BuckyResult<TransControlTaskGroupOutputResponse> {
        Self::control_task_group(self, req).await
    }
}
/*
struct TransHelper {

}

impl TransHelper {
    pub async fn download_chunk_sync(requestor: &TransRequestor, chunk_id: ChunkId, device_id: DeviceId) -> BuckyResult<Vec<u8>> {

        let local_path= cyfs_util::get_temp_path().join("trans_chunk").join(chunk_id.to_string());

        // 创建下载任务
        let req = TransStartTaskRequest {
            target: None,
            object_id: chunk_id.object_id().to_owned(),
            local_path: local_path.clone(),
            device_list: vec![device_id.clone()],
        };

        info!("will download chunk to tmp, chunk_id={}, tmp_file={}", chunk_id, local_path.display());

        requestor.start_task(&req).await.map_err(|e|{
            error!("trans start task error! chunk_id={}, {}", chunk_id, e);
            e
        })?;

        loop {
            let req = TransGetTaskStateRequest {
                target: None,
                object_id: chunk_id.object_id().to_owned(),
                local_path: local_path.clone(),
            };

            let state = requestor.get_task_state(&req).await.map_err(|e| {
                error!("get trans task state error! chunk={}, {}", chunk_id, e);
                e
            })?;

            match state {
                TransTaskState::Downloading(v) => {
                    // info!("trans task downloading! file_id={}, {:?}", chunk_id, v);
                }
                TransTaskState::Finished(_v) => {
                    info!("chunk trans task finished! chunk_id={}", chunk_id);
                    break;
                }
                TransTaskState::Canceled | TransTaskState::Paused | TransTaskState::Pending => {
                    unreachable!()
                }
            }

            async_std::task::sleep(std::time::Duration::from_secs(1)).await;
        }

        let mut f = async_std::fs::OpenOptions::new().read(true).open(&local_path).await.unwrap();
        let mut buf = vec![];
        let bytes = f.read_to_end(&mut buf).await.unwrap();
        if let Err(e) = async_std::fs::remove_file(&local_path).await {
            error!("remove tmp chunk file error!")
        }

        if bytes != chunk_id.len() {

        }
    }
}
*/