fetsig 0.25.0

Web-sys based browser fetch library using futures-signals with optional MAC.
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
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
use std::marker::PhantomData;

use artwrap::spawn_local;
use futures_signals::{
    map_ref,
    signal::{Mutable, Signal, SignalExt},
    signal_vec::{
        MutableSignalVec, MutableVec, MutableVecLockMut, MutableVecLockRef, SignalVec, SignalVecExt,
    },
};
use futures_signals_ext::{MutableExt, MutableVecExt};
use log::{debug, error, trace, warn};
use serde::{Serialize, de::DeserializeOwned};

#[cfg(feature = "json")]
use crate::JSONSerialize;
#[cfg(any(feature = "json", feature = "postcard"))]
use crate::MediaType;
#[cfg(feature = "postcard")]
use crate::PostcardSerialize;
use crate::{
    CollectionResponse, HEADER_SIGNATURE, MacSign, MacVerify, Messages, NoMac, Paging, StatusCode,
};

use super::{
    CollectionState,
    common::{PendingFetch, execute_fetch},
    request::Request,
    transferstate::TransferState,
};

pub struct CollectionStore<E, MV = NoMac> {
    transfer_state: Mutable<TransferState>,
    messages: Messages,
    paging: Mutable<Paging>,
    collection: MutableVec<E>,
    pmv: PhantomData<MV>,
}

impl<E, MV> CollectionStore<E, MV> {
    pub fn new() -> Self {
        Self::new_value(vec![])
    }

    pub fn new_value(collection: Vec<E>) -> Self {
        Self {
            transfer_state: Mutable::new(TransferState::Empty),
            messages: Messages::new(),
            paging: Mutable::new(Paging::default()),
            collection: MutableVec::new_with_values(collection),
            pmv: PhantomData,
        }
    }

    pub fn reset(&self) {
        self.transfer_state.set_neq(TransferState::Empty);
        self.messages.clear_all();
        self.paging.set(Paging::default());
        self.collection.lock_mut().clear();
    }

    pub fn invalidate(&self) {
        self.transfer_state.set_neq(TransferState::Empty);
    }

    pub fn transfer_state(&self) -> TransferState {
        self.transfer_state.get()
    }

    pub fn set_transfer_state(&self, transfer_state: TransferState) {
        self.transfer_state.set_neq(transfer_state);
    }

    pub fn reset_transfer_error(&self) {
        self.transfer_state.lock_mut().reset_error();
    }

    pub fn loaded(&self) -> bool {
        self.transfer_state.map(TransferState::loaded)
    }

    pub fn loaded_signal(&self) -> impl Signal<Item = bool> + use<E, MV> {
        self.transfer_state
            .signal_ref(TransferState::loaded)
            .dedupe()
    }

    pub fn loaded_status(&self) -> Option<StatusCode> {
        self.transfer_state.map(TransferState::loaded_status)
    }

    pub fn loaded_status_signal(&self) -> impl Signal<Item = Option<StatusCode>> + use<E, MV> {
        self.transfer_state
            .signal_ref(TransferState::loaded_status)
            .dedupe()
    }

    pub fn stored(&self) -> bool {
        self.transfer_state.map(TransferState::stored)
    }

    pub fn stored_signal(&self) -> impl Signal<Item = bool> + use<E, MV> {
        self.transfer_state
            .signal_ref(TransferState::stored)
            .dedupe()
    }

    pub fn stored_status(&self) -> Option<StatusCode> {
        self.transfer_state.map(TransferState::stored_status)
    }

    pub fn stored_status_signal(&self) -> impl Signal<Item = Option<StatusCode>> + use<E, MV> {
        self.transfer_state
            .signal_ref(TransferState::stored_status)
            .dedupe()
    }

    pub fn pending(&self) -> bool {
        self.transfer_state.map(TransferState::pending)
    }

    pub fn pending_signal(&self) -> impl Signal<Item = bool> + use<E, MV> {
        self.transfer_state
            .signal_ref(TransferState::pending)
            .dedupe()
    }

    pub fn collection(&self) -> &MutableVec<E> {
        &self.collection
    }

    pub fn messages(&self) -> &Messages {
        &self.messages
    }

    pub fn paging(&self) -> &Mutable<Paging> {
        &self.paging
    }

    pub fn is_empty(&self) -> bool {
        self.collection.lock_ref().is_empty()
    }

    pub fn any<F>(&self, f: F) -> bool
    where
        F: Fn(&E) -> bool,
    {
        self.collection.lock_ref().iter().any(f)
    }

    pub fn all<F>(&self, f: F) -> bool
    where
        F: Fn(&E) -> bool,
    {
        self.collection.lock_ref().iter().all(f)
    }

    pub fn lock_ref(&self) -> MutableVecLockRef<'_, E> {
        self.collection.lock_ref()
    }

    pub fn lock_mut(&self) -> MutableVecLockMut<'_, E> {
        self.collection.lock_mut()
    }

    pub fn inspect<F>(&self, f: F)
    where
        F: FnOnce(&[E]),
    {
        self.collection.inspect(f)
    }

    pub fn inspect_mut<F>(&self, f: F)
    where
        F: FnOnce(&mut MutableVecLockMut<E>),
    {
        self.collection.inspect_mut(f)
    }

    pub fn find_map<F, U>(&self, f: F) -> Option<U>
    where
        F: Fn(&E) -> Option<U>,
    {
        self.collection.lock_ref().iter().find_map(f)
    }

    pub fn map_vec<F, U>(&self, f: F) -> U
    where
        F: FnOnce(&[E]) -> U,
    {
        self.collection.map_vec(f)
    }

    pub fn map_vec_mut<F, U>(&self, f: F) -> U
    where
        F: FnOnce(&mut MutableVecLockMut<E>) -> U,
    {
        self.collection.map_vec_mut(f)
    }
}

impl<E, MV> CollectionStore<E, MV>
where
    E: Copy,
{
    pub fn empty_signal(&self) -> impl Signal<Item = bool> + use<E, MV> {
        self.collection.signal_vec().is_empty().dedupe()
    }

    pub fn collection_state_signal(&self) -> impl Signal<Item = CollectionState> + use<E, MV> {
        collection_state_signal(self.pending_signal(), self.empty_signal())
    }

    pub fn find<F>(&self, f: F) -> Option<E>
    where
        F: Fn(&E) -> bool,
    {
        self.find_map(|e| f(e).then_some(*e))
    }

    pub fn find_inspect_mut<P, F>(&self, predicate: P, f: F) -> Option<bool>
    where
        P: FnMut(&E) -> bool,
        F: FnMut(&mut E) -> bool,
    {
        self.collection.find_inspect_mut(predicate, f)
    }

    pub fn find_set<P>(&self, predicate: P, item: E) -> bool
    where
        P: FnMut(&E) -> bool,
    {
        self.collection.find_set(predicate, item)
    }

    pub fn find_set_or_add<P>(&self, predicate: P, item: E)
    where
        P: FnMut(&E) -> bool,
    {
        self.collection.find_set_or_add(predicate, item);
    }

    pub fn replace(&self, values: Vec<E>) -> Vec<E> {
        self.messages.clear_all();
        let mut collection = self.collection.lock_mut();
        let current = collection.drain(..).collect();
        collection.replace(values);
        current
    }

    pub fn remove<P>(&self, predicate: P) -> bool
    where
        P: FnMut(&E) -> bool,
    {
        self.collection.find_remove(predicate)
    }

    pub fn set_externally_loaded(&self, values: Vec<E>) {
        self.collection.lock_mut().replace(values);
        self.transfer_state
            .set_neq(TransferState::Loaded(StatusCode::Ok));
    }

    pub fn signal_map<F, U>(&self, f: F) -> impl Signal<Item = U> + use<E, MV, F, U>
    where
        F: FnMut(&[E]) -> U,
    {
        self.collection.signal_vec().to_signal_map(f)
    }

    pub fn signal_vec(&self) -> MutableSignalVec<E> {
        self.collection.signal_vec()
    }

    pub fn signal_vec_filter<F>(&self, f: F) -> impl SignalVec<Item = E> + use<E, MV, F>
    where
        F: FnMut(&E) -> bool,
    {
        self.collection.signal_vec_filter(f)
    }

    pub fn signal_vec_filter_signal<F, U>(
        &self,
        f: F,
    ) -> impl SignalVec<Item = E> + use<E, MV, F, U>
    where
        F: FnMut(&E) -> U,
        U: Signal<Item = bool>,
    {
        self.collection.signal_vec_filter_signal(f)
    }

    pub fn signal_vec_map<F, U>(&self, f: F) -> impl SignalVec<Item = U> + use<E, MV, F, U>
    where
        F: FnMut(E) -> U,
    {
        self.collection.signal_vec().map(f)
    }

    pub fn signal_vec_map_signal<F, U>(
        &self,
        f: F,
    ) -> impl SignalVec<Item = U::Item> + use<E, MV, F, U>
    where
        F: FnMut(E) -> U,
        U: Signal,
    {
        self.collection.signal_vec().map_signal(f)
    }

    pub fn signal_vec_filter_map<F, U>(&self, f: F) -> impl SignalVec<Item = U> + use<E, MV, F, U>
    where
        F: FnMut(E) -> Option<U>,
    {
        self.collection.signal_vec().filter_map(f)
    }
}

impl<E, MV> CollectionStore<E, MV>
where
    E: Clone,
{
    pub fn empty_signal_cloned(&self) -> impl Signal<Item = bool> + use<E, MV> {
        self.collection.signal_vec_cloned().is_empty().dedupe()
    }

    pub fn collection_state_signal_cloned(
        &self,
    ) -> impl Signal<Item = CollectionState> + use<E, MV> {
        collection_state_signal(self.pending_signal(), self.empty_signal_cloned())
    }

    pub fn find_cloned<F>(&self, f: F) -> Option<E>
    where
        F: Fn(&E) -> bool,
    {
        self.find_map(|e| f(e).then(|| e.clone()))
    }

    pub fn find_inspect_mut_cloned<P, F>(&self, predicate: P, f: F) -> Option<bool>
    where
        P: FnMut(&E) -> bool,
        F: FnMut(&mut E) -> bool,
    {
        self.collection.find_inspect_mut_cloned(predicate, f)
    }

    pub fn get_cloned(&self) -> Vec<E> {
        self.collection.lock_ref().to_vec()
    }

    pub fn find_set_cloned<P>(&self, predicate: P, item: E) -> bool
    where
        P: FnMut(&E) -> bool,
    {
        self.collection.find_set_cloned(predicate, item)
    }

    pub fn find_set_or_add_cloned<P>(&self, predicate: P, item: E)
    where
        P: FnMut(&E) -> bool,
    {
        self.collection.find_set_or_add_cloned(predicate, item);
    }

    pub fn replace_cloned(&self, values: Vec<E>) -> Vec<E> {
        self.messages.clear_all();
        let mut collection = self.collection.lock_mut();
        let current = collection.drain(..).collect();
        collection.replace_cloned(values);
        current
    }

    pub fn remove_cloned<P>(&self, predicate: P) -> bool
    where
        P: FnMut(&E) -> bool,
    {
        self.collection.find_remove_cloned(predicate)
    }

    pub fn set_externally_loaded_cloned(&self, values: Vec<E>) {
        self.collection.lock_mut().replace_cloned(values);
        self.transfer_state
            .set_neq(TransferState::Loaded(StatusCode::Ok));
    }

    pub fn signal_map_cloned<F, U>(&self, f: F) -> impl Signal<Item = U> + use<E, MV, F, U>
    where
        F: FnMut(&[E]) -> U,
    {
        self.collection.signal_vec_cloned().to_signal_map(f)
    }

    pub fn signal_vec_cloned(&self) -> MutableSignalVec<E> {
        self.collection.signal_vec_cloned()
    }

    pub fn signal_vec_filter_cloned<F>(&self, f: F) -> impl SignalVec<Item = E> + use<E, MV, F>
    where
        F: FnMut(&E) -> bool,
    {
        self.collection.signal_vec_filter_cloned(f)
    }

    pub fn signal_vec_filter_signal_cloned<F, U>(
        &self,
        f: F,
    ) -> impl SignalVec<Item = E> + use<E, MV, F, U>
    where
        F: FnMut(&E) -> U,
        U: Signal<Item = bool>,
    {
        self.collection.signal_vec_filter_signal_cloned(f)
    }

    pub fn signal_vec_map_cloned<F, U>(&self, f: F) -> impl SignalVec<Item = U> + use<E, MV, F, U>
    where
        F: FnMut(E) -> U,
    {
        self.collection.signal_vec_cloned().map(f)
    }

    pub fn signal_vec_map_signal_cloned<F, U>(
        &self,
        f: F,
    ) -> impl SignalVec<Item = U::Item> + use<E, MV, F, U>
    where
        F: FnMut(E) -> U,
        U: Signal,
    {
        self.collection.signal_vec_cloned().map_signal(f)
    }

    pub fn signal_vec_filter_map_cloned<F, U>(
        &self,
        f: F,
    ) -> impl SignalVec<Item = U> + use<E, MV, F, U>
    where
        F: FnMut(E) -> Option<U>,
    {
        self.collection.signal_vec_cloned().filter_map(f)
    }
}

impl<E, MV> CollectionStore<E, MV>
where
    E: Clone,
    MV: MacVerify,
{
    pub fn load<C>(&self, request: Request<'_>, result_callback: C)
    where
        E: DeserializeOwned + 'static,
        C: FnOnce(StatusCode) + 'static,
    {
        if self.transfer_state.map(TransferState::loaded) {
            if request.logging() {
                debug!("Request to load {} skipped, using cache", request.url());

                if !request.method().is_load() {
                    warn!(
                        "Load request unexpectedly uses store verb {:?}",
                        request.method().as_str()
                    );
                }
            }
        } else {
            self.load_skip_cache(request, result_callback);
        }
    }

    pub fn load_skip_cache<C>(&self, request: Request<'_>, result_callback: C)
    where
        E: DeserializeOwned + 'static,
        C: FnOnce(StatusCode) + 'static,
    {
        if request.logging() {
            debug!("Request to load {}", request.url());

            if !request.method().is_load() {
                warn!(
                    "Load request unexpectedly uses store verb {:?}",
                    request.method().as_str()
                );
            }
        }

        let collection = self.collection.clone();
        fetch::<_, _, _, MV>(
            request.with_is_load(true),
            self.transfer_state.clone(),
            self.messages.clone(),
            self.paging.clone(),
            move |new| {
                collection.lock_mut().replace_cloned(new);
            },
            result_callback,
        );
    }

    pub fn load_merge<F, C>(&self, request: Request<'_>, merge_fn: F, result_callback: C)
    where
        E: DeserializeOwned + 'static,
        F: FnMut(Vec<E>) + 'static,
        C: FnOnce(StatusCode) + 'static,
    {
        if request.logging() {
            debug!("Request to load/merge {}", request.url());

            if !request.method().is_load() {
                warn!(
                    "Load/merge request unexpectedly uses store verb {:?}",
                    request.method().as_str()
                );
            }
        }
        fetch::<_, _, _, MV>(
            request.with_is_load(true),
            self.transfer_state.clone(),
            self.messages.clone(),
            self.paging.clone(),
            merge_fn,
            result_callback,
        );
    }

    pub fn store<MS, C>(&self, request: Request<'_>, result_callback: C)
    where
        E: Serialize + DeserializeOwned + 'static,
        MS: MacSign,
        C: FnOnce(StatusCode) + 'static,
    {
        let mut request = request.with_is_load(false);
        if request.logging() {
            debug!("Request to update {}", request.url());

            if request.method().is_load() {
                warn!(
                    "Store request unexpectedly uses load verb {:?}",
                    request.method().as_str()
                );
            }
        }

        {
            // scope around vector and collection borrow
            let collection = self.lock_ref();
            if !collection.is_empty() {
                let media_type = match request.media_type() {
                    #[cfg(feature = "json")]
                    Some(media_type @ MediaType::Json) => media_type,
                    #[cfg(feature = "postcard")]
                    Some(media_type @ MediaType::Postcard) => media_type,
                    _ => {
                        if request.logging() {
                            warn!("Request failed as unsupported media type is requested");
                        }
                        self.messages.replace(Messages::from_service_error(
                            "Request failed as unsupported media type is requested",
                        ));
                        self.transfer_state
                            .lock_mut()
                            .stop(StatusCode::UnsupportedMediaType);
                        return;
                    }
                };

                let content = collection.to_vec();
                let bytes = match media_type {
                    #[cfg(feature = "json")]
                    MediaType::Json => content.to_json(),
                    #[cfg(feature = "postcard")]
                    MediaType::Postcard => content.to_postcard(),
                    _ => {
                        if request.logging() {
                            error!("Unsupported media type requested, unexpected code flow");
                        }
                        return;
                    }
                };
                let bytes = match bytes {
                    Ok(bytes) => bytes,
                    Err(error) => {
                        if request.logging() {
                            error!("Cannot serialize collection: {error}");
                        }
                        return;
                    }
                };

                if let Some(signature) = MS::sign(bytes.as_ref()) {
                    request = request.with_header(HEADER_SIGNATURE, signature);
                }

                request = request.with_body(bytes);
            }
        }

        let collection = self.collection.clone();
        fetch::<_, _, _, MV>(
            request,
            self.transfer_state.clone(),
            self.messages.clone(),
            self.paging.clone(),
            move |new| collection.lock_mut().replace_cloned(new),
            result_callback,
        );
    }
}

fn fetch<E, F, C, MV>(
    request: Request<'_>,
    transfer_state: Mutable<TransferState>,
    messages: Messages,
    paging: Mutable<Paging>,
    store_fn: F,
    result_callback: C,
) where
    E: Clone + DeserializeOwned + 'static,
    F: FnMut(Vec<E>) + 'static,
    C: FnOnce(StatusCode) + 'static,
    MV: MacVerify,
{
    let logging = request.logging();

    let pending_fetch = match request.start() {
        Ok(future) => future,
        Err(error) => {
            if logging {
                debug!("Request failed at init, error: {error}");
            }
            result_callback(StatusCode::BadRequest);
            transfer_state.lock_mut().stop(StatusCode::FetchFailed);
            return;
        }
    };
    if request.is_load() {
        transfer_state.lock_mut().start_load();
    } else {
        transfer_state.lock_mut().start_store();
    }

    let context = CollectionFetchContext::<F> {
        logging,
        messages,
        paging,
        store_fn,
    };

    spawn_local(async move {
        let status = execute_collection_fetch::<_, _, MV>(pending_fetch, context).await;
        result_callback(status);
        transfer_state.lock_mut().stop(status);
    });
}

async fn execute_collection_fetch<E, F, MV>(
    pending_fetch: PendingFetch,
    CollectionFetchContext {
        logging,
        messages,
        paging,
        mut store_fn,
    }: CollectionFetchContext<F>,
) -> StatusCode
where
    E: Clone + DeserializeOwned,
    F: FnMut(Vec<E>) + 'static,
    MV: MacVerify,
{
    let mut result = execute_fetch::<CollectionResponse<E>, MV>(pending_fetch).await;
    match (result.status(), result.take_response()) {
        (status @ StatusCode::FetchTimeout, _) => {
            if logging {
                // TODO: should this warning go also to Messages???
                debug!(
                    "Timeout accessing {}.",
                    result.hint().unwrap_or("?unknown url")
                );
            }
            status
        }
        (status @ StatusCode::FetchFailed, _) => {
            if logging {
                // TODO: should this warning go also to Messages???
                debug!(
                    "Request failed in execution, error: {}",
                    result.hint().unwrap_or("?unknown")
                );
            }
            status
        }
        (status @ StatusCode::DecodeFailed, _) => {
            if logging {
                // TODO: should this warning go also to Messages???
                warn!(
                    "Response decoding failed, error: {}",
                    result.hint().unwrap_or("?unknown")
                );
            }
            status
        }
        (status, None) => status,
        (status, Some(response)) => {
            let (response_entities, response_messages, response_paging) = response.take();
            messages.replace(response_messages);
            if status.is_success()
                && let Some(response_entities) = response_entities
            {
                if logging {
                    trace!("Request successfully fetched collection.");
                }
                store_fn(response_entities);
            }
            *paging.lock_mut() = response_paging;
            status
        }
    }
}

impl<E, MV> Default for CollectionStore<E, MV> {
    fn default() -> Self {
        Self::new()
    }
}

struct CollectionFetchContext<F> {
    logging: bool,
    messages: Messages,
    paging: Mutable<Paging>,
    store_fn: F,
}

pub fn collection_state_signal<P, E>(pending: P, empty: E) -> impl Signal<Item = CollectionState>
where
    P: Signal<Item = bool>,
    E: Signal<Item = bool>,
{
    map_ref! {
        pending, empty => {
            match (pending, empty) {
                (true, _) => CollectionState::Pending,
                (false, true) => CollectionState::Empty,
                (false, false) => CollectionState::NotEmpty,
            }
        }
    }
    .dedupe()
}