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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
use crate::base::*;
use cyfs_base::*;
use cyfs_core::*;
use cyfs_debug::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
pub struct NOCStorage {
id: String,
noc: Box<dyn NamedObjectCache>,
storage_id: StorageId,
last_update_time: AtomicU64,
device_id: DeviceId,
}
impl NOCStorage {
pub fn new(id: &str, noc: Box<dyn NamedObjectCache>) -> Self {
let storage: Storage = StorageObj::create(id, Vec::new());
Self {
id: id.to_owned(),
noc,
storage_id: storage.storage_id(),
last_update_time: AtomicU64::new(0),
device_id: DeviceId::default(),
}
}
pub fn id(&self) -> &str {
&self.id
}
pub async fn load(&self) -> BuckyResult<Option<Vec<u8>>> {
let req = NamedObjectCacheGetObjectRequest {
protocol: NONProtocol::Native,
source: self.device_id.clone(),
object_id: self.storage_id.object_id().to_owned(),
};
let resp = self.noc.get_object(&req).await?;
match resp {
Some(data) => match Storage::raw_decode(data.object_raw.as_ref().unwrap()) {
Ok((storage, _)) => {
let update_time = storage.body().as_ref().unwrap().update_time();
self.last_update_time.store(update_time, Ordering::Relaxed);
Ok(Some(storage.into_value()))
}
Err(e) => {
error!(
"decode storage object error: id={}, storage={}, {}",
self.id, self.storage_id, e
);
Err(e)
}
},
None => {
info!(
"storage not found in noc: id={}, storage={}",
self.id, self.storage_id
);
Ok(None)
}
}
}
pub async fn save(&self, buf: Vec<u8>) -> BuckyResult<()> {
info!(
"now will save storage to noc: id={}, storage={}",
self.id, self.storage_id
);
let mut storage: Storage = StorageObj::create(&self.id, buf);
let old_update_time = self.last_update_time.load(Ordering::Relaxed);
let mut now = storage.body().as_ref().unwrap().update_time();
if now < old_update_time {
warn!(
"storage new time is older than current! now={}, cur={}",
now, old_update_time
);
now = old_update_time + 1;
storage.body_mut().as_mut().unwrap().set_update_time(now);
}
assert_eq!(self.storage_id, storage.storage_id());
self.save_to_noc(storage).await
}
async fn save_to_noc(&self, storage: Storage) -> BuckyResult<()> {
let object_raw = storage.to_vec().unwrap();
let (object, _) = AnyNamedObject::raw_decode(&object_raw).unwrap();
let info = NamedObjectCacheInsertObjectRequest {
protocol: NONProtocol::Native,
source: self.device_id.clone(),
object_id: self.storage_id.object_id().to_owned(),
dec_id: None,
object_raw,
object: Arc::new(object),
flags: 0u32,
};
match self.noc.insert_object(&info).await {
Ok(resp) => {
match resp.result {
NamedObjectCacheInsertResult::Accept
| NamedObjectCacheInsertResult::Updated => {
info!(
"insert storage to noc success! id={}, storage={}",
self.id, self.storage_id
);
Ok(())
}
r @ _ => {
error!(
"update storage to noc but alreay exist! id={}, storage={}, result={:?}",
self.id, self.storage_id, r
);
Err(BuckyError::from(BuckyErrorCode::AlreadyExists))
}
}
}
Err(e) => {
error!(
"insert storage to noc error! id={}, storage={}, {}",
self.id, self.storage_id, e
);
Err(e)
}
}
}
pub async fn delete(&self) -> BuckyResult<()> {
let req = NamedObjectCacheDeleteObjectRequest {
protocol: NONProtocol::Native,
source: self.device_id.clone(),
object_id: self.storage_id.object_id().to_owned(),
flags: 0,
};
let resp = self.noc.delete_object(&req).await?;
if resp.deleted_count > 0 {
info!(
"delete storage object from noc successs: id={}, storage={}",
self.id, self.storage_id
);
} else {
warn!(
"delete storage object but not found: id={}, storage={}",
self.id, self.storage_id,
);
}
Ok(())
}
}
pub trait CollectionCodec<T> {
fn encode(&self) -> BuckyResult<Vec<u8>>;
fn decode(buf: &[u8]) -> BuckyResult<T>;
}
impl<T> CollectionCodec<T> for T
where
T: for<'de> RawDecode<'de> + RawEncode,
{
fn encode(&self) -> BuckyResult<Vec<u8>> {
self.to_vec()
}
fn decode(buf: &[u8]) -> BuckyResult<T> {
T::clone_from_slice(&buf)
}
}
#[macro_export]
macro_rules! declare_collection_codec_for_serde {
($T:ty) => {
impl CollectionCodec<$T> for $T {
fn encode(&self) -> cyfs_base::BuckyResult<Vec<u8>> {
let body = serde_json::to_string(&self).map_err(|e| {
let msg = format!("encode to json error! {}", e);
log::error!("{}", msg);
cyfs_base::BuckyError::new(cyfs_base::BuckyErrorCode::InvalidFormat, msg)
})?;
Ok(body.into_bytes())
}
fn decode(buf: &[u8]) -> cyfs_base::BuckyResult<$T> {
serde_json::from_slice(buf).map_err(|e| {
let msg = format!("decode from json error! {}", e);
log::error!("{}", msg);
cyfs_base::BuckyError::new(cyfs_base::BuckyErrorCode::InvalidFormat, msg)
})
}
}
};
}
#[macro_export]
macro_rules! declare_collection_codec_for_json_codec {
($T:ty) => {
impl CollectionCodec<$T> for $T {
fn encode(&self) -> cyfs_base::BuckyResult<Vec<u8>> {
Ok(self.encode_string().into())
}
fn decode(buf: &[u8]) -> cyfs_base::BuckyResult<$T> {
use std::str;
let str_value = str::from_utf8(buf).map_err(|e| {
let msg = format!("not valid utf8 string format: {}", e);
log::error!("{}", msg);
cyfs_base::BuckyError::new(cyfs_base::BuckyErrorCode::InvalidFormat, msg)
})?;
Self::decode_string(str_value)
}
}
};
}
pub struct NOCStorageWrapper {
storage: NOCStorage,
}
impl NOCStorageWrapper {
pub fn new(id: &str, noc: Box<dyn NamedObjectCache>) -> Self {
Self {
storage: NOCStorage::new(id, noc),
}
}
pub fn id(&self) -> &str {
self.storage.id()
}
pub async fn load<T>(&self) -> BuckyResult<Option<T>>
where
T: CollectionCodec<T>,
{
match self.storage.load().await? {
Some(buf) => {
let coll = T::decode(&buf).map_err(|e| {
error!(
"decode storage buf to collection failed! id={}, {}",
self.id(),
e
);
e
})?;
Ok(Some(coll))
}
None => Ok(None),
}
}
pub async fn save<T>(&self, data: &T) -> BuckyResult<()>
where
T: CollectionCodec<T>,
{
let buf = data.encode().map_err(|e| {
error!(
"convert collection to buf failed! id={}, {}",
self.storage.id, e
);
e
})?;
self.storage.save(buf).await
}
pub async fn delete(&self) -> BuckyResult<()> {
self.storage.delete().await
}
}
pub struct NOCCollection<T>
where
T: Default + CollectionCodec<T>,
{
coll: T,
storage: NOCStorageWrapper,
dirty: bool,
}
impl<T> NOCCollection<T>
where
T: Default + CollectionCodec<T>,
{
pub fn new(id: &str, noc: Box<dyn NamedObjectCache>) -> Self {
Self {
coll: T::default(),
storage: NOCStorageWrapper::new(id, noc),
dirty: false,
}
}
pub fn id(&self) -> &str {
self.storage.id()
}
pub fn coll(&self) -> &T {
&self.coll
}
pub fn is_dirty(&self) -> bool {
self.dirty
}
pub fn set_dirty(&mut self, dirty: bool) {
self.dirty = dirty;
}
pub fn swap(&mut self, mut value: T) -> T {
std::mem::swap(&mut self.coll, &mut value);
value
}
pub async fn load(&mut self) -> BuckyResult<()> {
match self.storage.load().await? {
Some(coll) => {
self.coll = coll;
Ok(())
}
None => Ok(()),
}
}
pub async fn save(&mut self) -> BuckyResult<()> {
if self.is_dirty() {
self.set_dirty(false);
self.storage.save(&self.coll).await.map_err(|e| {
self.set_dirty(true);
e
})
} else {
Ok(())
}
}
pub async fn delete(&mut self) -> BuckyResult<()> {
self.storage.delete().await?;
Ok(())
}
}
use std::ops::Deref;
use std::ops::DerefMut;
pub trait NOCCollectionWithLock<T>
where
T: Default + ?Sized + Send + 'static,
{
fn read(&self) -> Box<dyn Deref<Target = T> + '_>;
fn write(&self) -> Box<dyn DerefMut<Target = T> + '_>;
}
struct NOCCollectionWithMutex<T>
where
T: Default + ?Sized + Send + 'static,
{
coll: Mutex<T>,
}
impl<T> NOCCollectionWithMutex<T>
where
T: Default + ?Sized + Send + 'static,
{
fn new() -> Self {
Self {
coll: Mutex::new(T::default()),
}
}
}
impl<T> NOCCollectionWithLock<T> for NOCCollectionWithMutex<T>
where
T: Default + ?Sized + Send + 'static,
{
fn read(&self) -> Box<dyn Deref<Target = T> + '_> {
Box::new(self.coll.lock().unwrap())
}
fn write(&self) -> Box<dyn DerefMut<Target = T> + '_> {
Box::new(self.coll.lock().unwrap())
}
}
use std::sync::RwLock;
struct NOCCollectionWithRWLock<T>
where
T: Default + ?Sized + Send + 'static,
{
coll: RwLock<T>,
}
impl<T> NOCCollectionWithRWLock<T>
where
T: Default + ?Sized + Send + 'static,
{
fn new() -> Self {
Self {
coll: RwLock::new(T::default()),
}
}
}
impl<T> NOCCollectionWithLock<T> for NOCCollectionWithRWLock<T>
where
T: Default + ?Sized + Send + 'static,
{
fn read(&self) -> Box<dyn Deref<Target = T> + '_> {
Box::new(self.coll.read().unwrap())
}
fn write(&self) -> Box<dyn DerefMut<Target = T> + '_> {
Box::new(self.coll.write().unwrap())
}
}
pub struct NOCCollectionSync<T>
where
T: Default + CollectionCodec<T> + Send + 'static,
{
coll: Arc<Mutex<T>>,
storage: Arc<NOCStorage>,
dirty: Arc<AtomicBool>,
auto_save: Arc<AtomicBool>,
}
impl<T> Clone for NOCCollectionSync<T>
where
T: Default + CollectionCodec<T> + Send + 'static,
{
fn clone(&self) -> Self {
Self {
coll: self.coll.clone(),
storage: self.storage.clone(),
dirty: self.dirty.clone(),
auto_save: self.auto_save.clone(),
}
}
}
impl<T> NOCCollectionSync<T>
where
T: Default + CollectionCodec<T> + Send + 'static,
{
pub fn new(id: &str, noc: Box<dyn NamedObjectCache>) -> Self {
Self {
coll: Arc::new(Mutex::new(T::default())),
storage: Arc::new(NOCStorage::new(id, noc)),
dirty: Arc::new(AtomicBool::new(false)),
auto_save: Arc::new(AtomicBool::new(false)),
}
}
pub fn is_dirty(&self) -> bool {
self.dirty.load(Ordering::SeqCst)
}
pub fn set_dirty(&self, dirty: bool) -> bool {
self.dirty.swap(dirty, Ordering::SeqCst)
}
pub fn coll(&self) -> &Arc<Mutex<T>> {
&self.coll
}
pub fn id(&self) -> &str {
self.storage.id()
}
pub fn swap(&mut self, mut value: T) -> T {
{
let mut cur = self.coll.lock().unwrap();
std::mem::swap(&mut *cur, &mut value);
}
self.set_dirty(true);
value
}
pub async fn load(&self) -> BuckyResult<()> {
match self.storage.load().await? {
Some(buf) => {
let coll = T::decode(&buf).map_err(|e| {
error!(
"decode storage buf to collection failed! id={}, {}",
self.id(),
e
);
e
})?;
*self.coll.lock().unwrap() = coll;
Ok(())
}
None => Ok(()),
}
}
pub async fn save(&self) -> BuckyResult<()> {
if self.set_dirty(false) {
self.save_impl().await.map_err(|e| {
self.set_dirty(true);
e
})
} else {
Ok(())
}
}
pub fn async_save(&self) {
let this = self.clone();
async_std::task::spawn(async move {
let _r = this.save().await;
});
}
async fn save_impl(&self) -> BuckyResult<()> {
let buf = {
let coll = self.coll.lock().unwrap();
coll.encode().map_err(|e| {
error!(
"convert collection to buf failed! id={}, {}",
self.storage.id, e
);
e
})?
};
self.storage.save(buf).await
}
pub async fn delete(&self) -> BuckyResult<()> {
self.storage.delete().await?;
self.stop_save();
Ok(())
}
pub fn start_save(&self, dur: std::time::Duration) {
use async_std::prelude::*;
let ret = self
.auto_save
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire);
if ret.is_err() {
warn!("storage already in saving state! id={}", self.id());
return;
}
let this = self.clone();
async_std::task::spawn(async move {
let mut interval = async_std::stream::interval(dur);
while let Some(_) = interval.next().await {
if !this.auto_save.load(Ordering::SeqCst) {
warn!("storage auto save stopped! id={}", this.id());
break;
}
let _ = this.save().await;
}
});
}
pub fn stop_save(&self) {
if let Ok(_) =
self.auto_save
.compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
{
info!("will stop storage auto save! id={}", self.id());
}
}
}
pub struct NOCCollectionRWSync<T>
where
T: Default + CollectionCodec<T> + Send + Sync + 'static,
{
coll: Arc<RwLock<T>>,
storage: Arc<NOCStorage>,
dirty: Arc<AtomicBool>,
auto_save: Arc<AtomicBool>,
}
impl<T> Clone for NOCCollectionRWSync<T>
where
T: Default + CollectionCodec<T> + Send + Sync + 'static,
{
fn clone(&self) -> Self {
Self {
coll: self.coll.clone(),
storage: self.storage.clone(),
dirty: self.dirty.clone(),
auto_save: self.auto_save.clone(),
}
}
}
impl<T> NOCCollectionRWSync<T>
where
T: Default + CollectionCodec<T> + Send + Sync + 'static,
{
pub fn new(id: &str, noc: Box<dyn NamedObjectCache>) -> Self {
Self {
coll: Arc::new(RwLock::new(T::default())),
storage: Arc::new(NOCStorage::new(id, noc)),
dirty: Arc::new(AtomicBool::new(false)),
auto_save: Arc::new(AtomicBool::new(false)),
}
}
pub fn is_dirty(&self) -> bool {
self.dirty.load(Ordering::SeqCst)
}
pub fn set_dirty(&self, dirty: bool) {
self.dirty.store(dirty, Ordering::SeqCst);
}
pub fn coll(&self) -> &Arc<RwLock<T>> {
&self.coll
}
pub fn id(&self) -> &str {
self.storage.id()
}
pub fn swap(&self, mut value: T) -> T {
{
let mut cur = self.coll.write().unwrap();
std::mem::swap(&mut *cur, &mut value);
}
self.set_dirty(true);
value
}
pub async fn load(&self) -> BuckyResult<()> {
match self.storage.load().await? {
Some(buf) => {
let coll = T::decode(&buf).map_err(|e| {
error!(
"decode storage buf to collection failed! id={}, {}",
self.id(),
e
);
e
})?;
*self.coll.write().unwrap() = coll;
Ok(())
}
None => Ok(()),
}
}
pub async fn save(&self) -> BuckyResult<()> {
if self.is_dirty() {
self.set_dirty(false);
self.save_impl().await.map_err(|e| {
self.set_dirty(true);
e
})
} else {
Ok(())
}
}
pub async fn save_impl(&self) -> BuckyResult<()> {
let buf = {
let coll = self.coll.read().unwrap();
coll.encode().map_err(|e| {
error!(
"convert collection to buf failed! id={}, {}",
self.storage.id, e
);
e
})?
};
self.storage.save(buf).await
}
pub async fn delete(&mut self) -> BuckyResult<()> {
self.storage.delete().await?;
self.stop_save();
Ok(())
}
pub fn start_save(&self, dur: std::time::Duration) {
use async_std::prelude::*;
let ret = self
.auto_save
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire);
if ret.is_err() {
warn!("storage already in saving state! id={}", self.id());
return;
}
let this = self.clone();
async_std::task::spawn(async move {
let mut interval = async_std::stream::interval(dur);
while let Some(_) = interval.next().await {
if !this.auto_save.load(Ordering::SeqCst) {
warn!("storage auto save stopped! id={}", this.id());
break;
}
let _ = this.save().await;
}
});
}
pub fn stop_save(&self) {
if let Ok(_) =
self.auto_save
.compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
{
info!("will stop storage auto save! id={}", self.id());
}
}
}