cyfs_lib/non/
def.rs

1use crate::{ndn::*, NamedObjectCachePutObjectResult, rmeta::ObjectSelectorDataProvider};
2use cyfs_base::*;
3
4use serde_json::{Map, Value};
5use std::fmt;
6use std::str::FromStr;
7use std::sync::Arc;
8use std::borrow::Cow;
9
10// 请求的数据类型
11#[derive(Clone)]
12pub enum NONDataType {
13    // 请求一个object
14    Object = 0,
15
16    // 请求对应的数据
17    Data = 1,
18}
19
20impl ToString for NONDataType {
21    fn to_string(&self) -> String {
22        (match *self {
23            Self::Object => "object",
24            Self::Data => "data",
25        })
26        .to_owned()
27    }
28}
29
30impl FromStr for NONDataType {
31    type Err = BuckyError;
32
33    fn from_str(value: &str) -> Result<Self, Self::Err> {
34        let ret = match value {
35            "object" => Self::Object,
36            "data" => Self::Data,
37            v @ _ => {
38                let msg = format!("unknown non datatype: {}", v);
39                error!("{}", msg);
40
41                return Err(BuckyError::new(BuckyErrorCode::InvalidData, msg));
42            }
43        };
44
45        Ok(ret)
46    }
47}
48
49#[derive(Debug, Eq, PartialEq)]
50pub enum NONAction {
51    // non
52    PutObject,
53    GetObject,
54    PostObject,
55    SelectObject,
56    DeleteObject,
57}
58
59impl ToString for NONAction {
60    fn to_string(&self) -> String {
61        (match *self {
62            Self::PutObject => "put-object",
63            Self::GetObject => "get-object",
64            Self::PostObject => "post-object",
65            Self::SelectObject => "select-object",
66            Self::DeleteObject => "delete-object",
67        })
68        .to_owned()
69    }
70}
71
72impl FromStr for NONAction {
73    type Err = BuckyError;
74
75    fn from_str(value: &str) -> Result<Self, Self::Err> {
76        let ret = match value {
77            "put-object" => Self::PutObject,
78            "get-object" => Self::GetObject,
79            "post-object" => Self::PostObject,
80            "select-object" => Self::SelectObject,
81            "delete-object" => Self::DeleteObject,
82            v @ _ => {
83                let msg = format!("unknown non action: {}", v);
84                error!("{}", msg);
85
86                return Err(BuckyError::new(BuckyErrorCode::InvalidData, msg));
87            }
88        };
89
90        Ok(ret)
91    }
92}
93
94// non操作的缺省行为,默认为NON
95#[derive(Clone, Debug, Eq, PartialEq)]
96pub enum NONAPILevel {
97    NOC = 0,
98    NON = 1,
99    Router = 2,
100}
101
102impl Default for NONAPILevel {
103    fn default() -> Self {
104        Self::Router
105    }
106}
107
108impl Into<NDNAPILevel> for NONAPILevel {
109    fn into(self) -> NDNAPILevel {
110        match self {
111            Self::NOC => NDNAPILevel::NDC,
112            Self::NON => NDNAPILevel::NDN,
113            Self::Router => NDNAPILevel::Router,
114        }
115    }
116}
117
118impl ToString for NONAPILevel {
119    fn to_string(&self) -> String {
120        (match *self {
121            Self::NON => "non",
122            Self::NOC => "noc",
123            Self::Router => "router",
124        })
125        .to_owned()
126    }
127}
128
129impl FromStr for NONAPILevel {
130    type Err = BuckyError;
131
132    fn from_str(value: &str) -> Result<Self, Self::Err> {
133        let ret = match value {
134            "non" => Self::NON,
135            "noc" => Self::NOC,
136            "router" => Self::Router,
137            v @ _ => {
138                let msg = format!("unknown non api level: {}", v);
139                error!("{}", msg);
140
141                return Err(BuckyError::new(BuckyErrorCode::UnSupport, msg));
142            }
143        };
144
145        Ok(ret)
146    }
147}
148
149#[derive(Clone, Debug, Eq, PartialEq)]
150pub enum NONPutObjectResult {
151    Accept,
152    AcceptWithSign,
153    AlreadyExists,
154    Updated,
155    Merged,
156}
157
158impl ToString for NONPutObjectResult {
159    fn to_string(&self) -> String {
160        (match *self {
161            Self::Accept => "Accept",
162            Self::AcceptWithSign => "AcceptWithSign",
163            Self::AlreadyExists => "AlreadyExists",
164            Self::Updated => "Updated",
165            Self::Merged => "Merged",
166        })
167        .to_owned()
168    }
169}
170
171impl FromStr for NONPutObjectResult {
172    type Err = BuckyError;
173
174    fn from_str(value: &str) -> Result<Self, Self::Err> {
175        let ret = match value {
176            "Accept" => Self::Accept,
177            "AcceptWithSign" => Self::AcceptWithSign,
178            "AlreadyExists" => Self::AlreadyExists,
179            "Updated" => Self::Updated,
180            "Merged" => Self::Merged,
181            v @ _ => {
182                let msg = format!("unknown NONPutObjectResult: {}", v);
183                error!("{}", msg);
184
185                return Err(BuckyError::new(BuckyErrorCode::InvalidData, msg));
186            }
187        };
188
189        Ok(ret)
190    }
191}
192
193impl Into<NONPutObjectResult> for NamedObjectCachePutObjectResult {
194    fn into(self) -> NONPutObjectResult {
195        match self {
196            Self::Accept => NONPutObjectResult::Accept,
197            Self::AlreadyExists => NONPutObjectResult::AlreadyExists,
198            Self::Updated => NONPutObjectResult::Updated,
199            Self::Merged => NONPutObjectResult::Merged,
200        }
201    }
202}
203
204impl Into<NamedObjectCachePutObjectResult> for NONPutObjectResult {
205    fn into(self) -> NamedObjectCachePutObjectResult {
206        match self {
207            Self::Accept | Self::AcceptWithSign => NamedObjectCachePutObjectResult::Accept,
208            Self::AlreadyExists => NamedObjectCachePutObjectResult::AlreadyExists,
209            Self::Updated => NamedObjectCachePutObjectResult::Updated,
210            Self::Merged => NamedObjectCachePutObjectResult::Merged,
211        }
212    }
213}
214
215#[derive(Clone)]
216pub struct NONObjectInfo {
217    pub object_id: ObjectId,
218    pub object_raw: Vec<u8>,
219
220    // 可选,用以内部直接使用
221    pub object: Option<Arc<AnyNamedObject>>,
222}
223
224impl NONObjectInfo {
225    pub fn new(
226        object_id: ObjectId,
227        object_raw: Vec<u8>,
228        object: Option<Arc<AnyNamedObject>>,
229    ) -> Self {
230        Self {
231            object_id,
232            object_raw,
233            object,
234        }
235    }
236
237    pub fn new_from_object_raw(object_raw: Vec<u8>) -> BuckyResult<Self> {
238        let (object, _) = AnyNamedObject::raw_decode(&object_raw).map_err(|e| {
239            error!("decode object from object_raw error: {}", e,);
240            e
241        })?;
242
243        let object_id = object.object_id();
244        Ok(Self::new(object_id, object_raw, Some(Arc::new(object))))
245    }
246
247    pub fn is_empty(&self) -> bool {
248        self.object_raw.is_empty()
249    }
250    
251    pub fn object(&self) -> &Arc<AnyNamedObject> {
252        self.object.as_ref().unwrap()
253    }
254
255
256    pub fn object_if_none_then_decode(&self) -> BuckyResult<Cow<AnyNamedObject>> {
257        match &self.object {
258            Some(object) => {
259                Ok(Cow::Borrowed(object.as_ref()))
260            }
261            None => {
262                let (object, _) = AnyNamedObject::raw_decode(&self.object_raw).map_err(|e| {
263                    error!(
264                        "decode object from object_raw error: obj={} {}",
265                        self.object_id, e,
266                    );
267                    e
268                })?;
269
270                Ok(Cow::Owned(object))
271            }
272        }
273    }
274
275    pub fn take_object(&mut self) -> Arc<AnyNamedObject> {
276        self.object.take().unwrap()
277    }
278
279    pub fn clone_object(&self) -> Arc<AnyNamedObject> {
280        self.object.as_ref().unwrap().clone()
281    }
282    pub fn try_decode(&mut self) -> BuckyResult<()> {
283        if self.object.is_none() {
284            self.decode()
285        } else {
286            Ok(())
287        }
288    }
289
290    pub fn decode(&mut self) -> BuckyResult<()> {
291        assert!(self.object.is_none());
292
293        let (object, _) = AnyNamedObject::raw_decode(&self.object_raw).map_err(|e| {
294            error!(
295                "decode object from object_raw error: obj={} {}",
296                self.object_id, e,
297            );
298            e
299        })?;
300
301        self.object = Some(Arc::new(object));
302        Ok(())
303    }
304
305    pub fn verify(&self) -> BuckyResult<()> {
306        let calc_id = if let Some(object) = &self.object {
307            object.calculate_id()
308        } else {
309            let (object, _) = AnyNamedObject::raw_decode(&self.object_raw).map_err(|e| {
310                error!(
311                    "decode object from object_raw error: obj={} {}",
312                    self.object_id, e,
313                );
314                e
315            })?;
316
317            object.calculate_id()
318        };
319        
320        // 校验id
321        if calc_id != self.object_id {
322            let msg = format!("unmatch object id: {}, calc={}", self.object_id, calc_id);
323            error!("{}", msg);
324            return Err(BuckyError::new(BuckyErrorCode::Unmatch, msg));
325        }
326
327        Ok(())
328    }
329
330    pub fn decode_and_verify(&mut self) -> BuckyResult<()> {
331        self.decode()?;
332        self.verify()
333    }
334
335    pub fn get_update_time(&mut self) -> BuckyResult<u64> {
336        self.try_decode()?;
337
338        let object = self.object.as_ref().unwrap();
339        let t = object.get_update_time();
340        if t > 0 {
341            debug!("object update time: {}, {}", self.object_id, t);
342        }
343
344        Ok(t)
345    }
346
347    pub fn get_expired_time(&mut self) -> BuckyResult<Option<u64>> {
348        self.try_decode()?;
349
350        let object = self.object.as_ref().unwrap();
351        let t = object.expired_time();
352        if let Some(t) = &t {
353            debug!("object expired time: {}, {}", self.object_id, t);
354        }
355
356        Ok(t)
357    }
358}
359
360impl fmt::Debug for NONObjectInfo {
361    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362        fmt::Display::fmt(self, f)
363    }
364}
365
366impl fmt::Display for NONObjectInfo {
367    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368        write!(
369            f,
370            "object_id: {}, len: {}",
371            self.object_id,
372            self.object_raw.len(),
373        )?;
374
375        if let Some(obj) = &self.object {
376            write!(
377                f,
378                ", obj_type: {}",
379                obj.obj_type()
380            )?;
381        }
382
383        Ok(())
384    }
385}
386
387impl JsonCodec<NONObjectInfo> for NONObjectInfo {
388    fn encode_json(&self) -> Map<String, Value> {
389        let mut obj = Map::new();
390
391        obj.insert(
392            "object_raw".to_owned(),
393            Value::String(hex::encode(&self.object_raw)),
394        );
395
396        obj.insert(
397            "object_id".to_owned(),
398            Value::String(self.object_id.to_string()),
399        );
400
401        obj
402    }
403
404    fn decode_json(obj: &Map<String, Value>) -> BuckyResult<NONObjectInfo> {
405        let object_id: ObjectId = JsonCodecHelper::decode_string_field(obj, "object_id")?;
406
407        let object_raw: String = JsonCodecHelper::decode_string_field(obj, "object_raw")?;
408        let object_raw = hex::decode(&object_raw).map_err(|e| {
409            let msg = format!("invalid object_raw hex buffer! {}", e);
410            error!("{}", msg);
411
412            BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
413        })?;
414
415        let mut object = NONObjectInfo::new(object_id, object_raw, None);
416        object.decode_and_verify()?;
417
418        Ok(object)
419    }
420}
421
422
423impl ObjectFormat for NONObjectInfo {
424    fn format_json(&self) -> serde_json::Value {
425        let obj = self.object();
426        if obj.obj_type_code() != ObjectTypeCode::Custom {
427            obj.format_json()
428        } else {
429            let obj_type = obj.obj_type();
430            match FORMAT_FACTORY.format(obj_type, &self.object_raw) {
431                Some(ret) => ret,
432                None => obj.format_json(),
433            }
434        }
435    }
436}
437
438impl RawEncode for NONObjectInfo {
439    fn raw_measure(&self, purpose: &Option<RawEncodePurpose>) -> Result<usize, BuckyError> {
440        self.object_raw.raw_measure(purpose)
441    }
442
443    fn raw_encode<'a>(
444        &self,
445        buf: &'a mut [u8],
446        purpose: &Option<RawEncodePurpose>,
447    ) -> Result<&'a mut [u8], BuckyError> {
448        self.object_raw.raw_encode(buf, purpose)
449    }
450}
451
452impl<'de> RawDecode<'de> for NONObjectInfo {
453    fn raw_decode(buf: &'de [u8]) -> Result<(Self, &'de [u8]), BuckyError> {
454        let (object_raw, buf) = Vec::raw_decode(buf)?;
455        let ret = Self::new_from_object_raw(object_raw)?;
456
457        Ok((ret, buf))
458    }
459}
460
461#[derive(Clone)]
462pub struct NONSlimObjectInfo {
463    pub object_id: ObjectId,
464    pub object_raw: Option<Vec<u8>>,
465    pub object: Option<Arc<AnyNamedObject>>,
466}
467
468impl fmt::Debug for NONSlimObjectInfo {
469    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
470        fmt::Display::fmt(&self, f)
471    }
472}
473
474impl fmt::Display for NONSlimObjectInfo {
475    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
476        write!(f, "object_id: {}", self.object_id)?;
477        if let Some(object_raw) = &self.object_raw {
478            write!(f, ", len: {}", object_raw.len())?;
479        }
480
481        Ok(())
482    }
483}
484
485impl NONSlimObjectInfo {
486    pub fn new(object_id: ObjectId, object_raw: Option<Vec<u8>>, object: Option<Arc<AnyNamedObject>>) -> Self {
487        Self {
488            object_id,
489            object_raw,
490            object,
491        }
492    }
493
494    pub fn is_empty(&self) -> bool {
495        self.object_raw.is_none() && self.object.is_none()
496    }
497
498    pub fn decode(&mut self) -> BuckyResult<()> {
499        assert!(self.object.is_none());
500
501        if let Some(object_raw) = &self.object_raw {
502            let (object, _) = AnyNamedObject::raw_decode(&object_raw).map_err(|e| {
503                error!(
504                    "decode object from object_raw error: obj={} {}",
505                    self.object_id, e,
506                );
507                e
508            })?;
509            self.object = Some(Arc::new(object));
510        }
511        Ok(())
512    }
513
514    pub fn verify(&self) -> BuckyResult<()> {
515        let calc_id = if let Some(object) = &self.object {
516            object.calculate_id()
517        } else if let Some(object_raw) = &self.object_raw {
518            let (object, _) = AnyNamedObject::raw_decode(&object_raw).map_err(|e| {
519                error!(
520                    "decode object from object_raw error: obj={} {}",
521                    self.object_id, e,
522                );
523                e
524            })?;
525
526            object.calculate_id()
527        } else {
528            return Ok(());
529        };
530
531        // 校验id
532        if calc_id != self.object_id {
533            let msg = format!("unmatch object id: {}, calc={}", self.object_id, calc_id);
534            error!("{}", msg);
535            return Err(BuckyError::new(BuckyErrorCode::Unmatch, msg));
536        }
537
538        Ok(())
539    }
540
541    pub fn decode_and_verify(&mut self) -> BuckyResult<()> {
542        if self.object_raw.is_some() && self.object.is_none() {
543            self.decode()?;
544        }
545        
546        self.verify()
547    }
548}
549
550impl JsonCodec<NONSlimObjectInfo> for NONSlimObjectInfo {
551    fn encode_json(&self) -> Map<String, Value> {
552        let mut obj = Map::new();
553
554        if let Some(object_raw) = &self.object_raw {
555            obj.insert(
556                "object_raw".to_owned(),
557                Value::String(hex::encode(object_raw)),
558            );
559        } else if let Some(object) = &self.object {
560            let object_raw = object.to_vec().unwrap();
561            obj.insert(
562                "object_raw".to_owned(),
563                Value::String(hex::encode(object_raw)),
564            );
565        }
566
567        obj.insert(
568            "object_id".to_owned(),
569            Value::String(self.object_id.to_string()),
570        );
571
572        obj
573    }
574
575    fn decode_json(obj: &Map<String, Value>) -> BuckyResult<Self> {
576        let object_id: ObjectId = JsonCodecHelper::decode_string_field(obj, "object_id")?;
577
578        let object_raw: Option<String> =
579            JsonCodecHelper::decode_option_string_field(obj, "object_raw")?;
580        let object_raw = if let Some(object_raw) = object_raw {
581            let object_raw = hex::decode(&object_raw).map_err(|e| {
582                let msg = format!("invalid object_raw hex buffer! {}", e);
583                error!("{}", msg);
584                BuckyError::new(BuckyErrorCode::InvalidFormat, msg)
585            })?;
586
587            Some(object_raw)
588        } else {
589            None
590        };
591
592        let mut object = Self::new(object_id, object_raw, None);
593        object.decode_and_verify()?;
594
595        Ok(object)
596    }
597}
598
599impl Into<NONSlimObjectInfo> for NONObjectInfo {
600    fn into(self) -> NONSlimObjectInfo {
601        NONSlimObjectInfo::new(self.object_id, Some(self.object_raw), self.object)
602    }
603}
604
605
606impl ObjectSelectorDataProvider for NONObjectInfo {
607    fn object_id(&self) -> &ObjectId {
608        &self.object_id
609    }
610    fn obj_type(&self) -> u16 {
611        self.object().obj_type()
612    }
613
614    fn object_dec_id(&self) -> &Option<ObjectId> {
615        self.object().dec_id()
616    }
617    fn object_author(&self) -> &Option<ObjectId> {
618        self.object().author()
619    }
620    fn object_owner(&self) -> &Option<ObjectId> {
621        self.object().owner()
622    }
623
624    fn object_create_time(&self) -> Option<u64> {
625        self.object().option_create_time()
626    }
627
628    fn object_update_time(&self) -> Option<u64> {
629        self.object().update_time()
630    }
631    fn object_expired_time(&self) -> Option<u64> {
632        self.object().expired_time()
633    }
634
635    fn update_time(&self) -> &u64 {
636        &0
637    }
638    fn insert_time(&self) -> &u64 {
639        &0
640    }
641}