artemis-normalized-cache 0.1.0-alpha.0

A graph-based normalized cache exchange for the artemis crate.
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
use crate::{cache_exchange::NormalizedCacheExchange, NormalizedCacheExtension, QueryStore};
use artemis::{
    exchange::{
        Client, Exchange, ExchangeFactory, ExchangeResult, Operation, OperationMeta,
        OperationOptions, OperationResult
    },
    utils::progressive_hash,
    DebugInfo, Error, GraphQLQuery, RequestPolicy, Response, ResultSource
};
use artemis_test::{
    add_conference::{add_conference, add_conference::AddConferenceAddConference, AddConference},
    get_conference::{
        get_conference::{GetConferenceConference, ResponseData, Variables},
        GetConference
    },
    get_conferences::{
        get_conferences, get_conferences::GetConferencesConferences, GetConferences
    }
};
use racetrack::{track_with, Tracker};
use serde::de::DeserializeOwned;
use std::{any::Any, collections::HashSet, sync::Arc};

fn make_op_with_key<Q: GraphQLQuery>(
    _query: Q,
    variables: Q::Variables,
    key: u64
) -> Operation<Q::Variables> {
    let (query, meta) = Q::build_query(variables);
    Operation {
        key,
        query,
        meta: OperationMeta {
            query_key: key as u32,
            ..meta
        },
        options: OperationOptions {
            url: "http://0.0.0.0".parse().unwrap(),
            request_policy: RequestPolicy::CacheFirst,
            extra_headers: None,
            extensions: None
        }
    }
}

fn make_op<Q: GraphQLQuery>(_query: Q, variables: Q::Variables) -> Operation<Q::Variables> {
    let (query, meta) = Q::build_query(variables);
    Operation {
        key: progressive_hash(meta.query_key, &query.variables),
        query,
        meta,
        options: OperationOptions {
            url: "http://0.0.0.0".parse().unwrap(),
            request_policy: RequestPolicy::CacheFirst,
            extra_headers: None,
            extensions: None
        }
    }
}

#[tokio::test]
async fn writes_queries_to_cache() {
    struct Fetch;
    #[async_trait]
    impl Exchange for Fetch {
        async fn run<Q: GraphQLQuery, C: Client>(
            &self,
            operation: Operation<Q::Variables>,
            _client: C
        ) -> ExchangeResult<Q::ResponseData> {
            let response_data = ResponseData {
                conference: Some(GetConferenceConference {
                    id: "1".to_string(),
                    name: "test".to_string(),
                    talks: None,
                    city: None
                })
            };

            make_result::<Q>(operation, Box::new(response_data))
        }
    }

    let client = DummyClient {
        tracker: Tracker::new()
    };
    let variables = Variables {
        id: "1".to_string()
    };

    let operation = make_op_with_key(GetConference, variables.clone(), 1);

    let exchange = NormalizedCacheExchange::new().build(Fetch);
    exchange
        .run::<GetConference, _>(operation.clone(), client.clone())
        .await
        .unwrap();
    let result = exchange
        .run::<GetConference, _>(operation.clone(), client.clone())
        .await;
    assert!(result.is_ok(), "Operation returned an error");
    let result = result.unwrap();

    assert_eq!(
        result.response.debug_info.unwrap().source,
        ResultSource::Cache,
        "Result didn't come from the cache"
    );
}

lazy_static! {
    static ref TRACKER: Arc<Tracker> = Tracker::new();
}

fn make_result<Q: GraphQLQuery>(
    operation: Operation<Q::Variables>,
    data: Box<dyn Any>
) -> ExchangeResult<Q::ResponseData> {
    let data = *data.downcast::<Q::ResponseData>().unwrap();
    Ok(OperationResult {
        key: operation.key,
        meta: operation.meta,
        response: Response {
            debug_info: Some(DebugInfo {
                source: ResultSource::Network,
                did_dedup: false
            }),
            errors: None,
            data: Some(data)
        }
    })
}

#[derive(Clone)]
struct DummyClient {
    tracker: Arc<Tracker>
}
#[track_with(tracker, namespace = "Client")]
impl Client for DummyClient {
    fn rerun_query(&self, _query_key: u64) {}

    fn push_result<R>(&self, _query_key: u64, _result: ExchangeResult<R>)
    where
        R: DeserializeOwned + Send + Sync + Clone + 'static
    {
    }
}

#[tokio::test]
async fn updates_related_queries() {
    let tracker = Tracker::new();

    struct Fetch {
        tracker: Arc<Tracker>
    }
    #[track_with(tracker)]
    #[async_trait]
    impl Exchange for Fetch {
        async fn run<Q: GraphQLQuery, C: Client>(
            &self,
            operation: Operation<Q::Variables>,
            _client: C
        ) -> ExchangeResult<Q::ResponseData> {
            let data_single = ResponseData {
                conference: Some(GetConferenceConference {
                    id: "1".to_string(),
                    name: "test".to_string(),
                    talks: None,
                    city: None
                })
            };
            let data_multi = get_conferences::ResponseData {
                conferences: Some(vec![GetConferencesConferences {
                    id: "1".to_string(),
                    name: "test".to_string()
                }])
            };

            let query_key = operation.meta.query_key.clone();

            // This needs to be calculated at runtime because bincode is platform specific
            if query_key == 1 {
                make_result::<Q>(operation, Box::new(data_single))
            } else if query_key == 2 {
                make_result::<Q>(operation, Box::new(data_multi))
            } else {
                panic!("Exchange got called with invalid query {}", query_key)
            }
        }
    }

    let variables = Variables {
        id: "1".to_string()
    };
    let operation_single = make_op_with_key(GetConference, variables, 1);
    let operation_multiple = make_op_with_key(GetConferences, get_conferences::Variables, 2);

    let client = DummyClient {
        tracker: tracker.clone()
    };
    let dummy_exchange = Fetch {
        tracker: tracker.clone()
    };
    let exchange = NormalizedCacheExchange::new().build(dummy_exchange);

    let res = exchange
        .run::<GetConference, _>(operation_single, client.clone())
        .await;
    assert!(res.is_ok());
    tracker.assert_that("Fetch::run").was_called_once();

    let res = exchange
        .run::<GetConferences, _>(operation_multiple, client.clone())
        .await;
    assert!(res.is_ok());
    tracker.assert_that("Fetch::run").was_called_times(2);
    tracker
        .assert_that("Client::rerun_query")
        .was_called_once()
        .with((1u64));
}

#[tokio::test]
async fn does_nothing_when_no_related_queries_have_changed() {
    let tracker = Tracker::new();

    struct Fetch(Arc<Tracker>);
    #[track_with(0)]
    #[async_trait]
    impl Exchange for Fetch {
        async fn run<Q: GraphQLQuery, C: Client>(
            &self,
            operation: Operation<Q::Variables>,
            _client: C
        ) -> ExchangeResult<Q::ResponseData> {
            let data_one = ResponseData {
                conference: Some(GetConferenceConference {
                    id: "1".to_string(),
                    name: "test".to_string(),
                    talks: None,
                    city: None
                })
            };
            let data_unrelated = ResponseData {
                conference: Some(GetConferenceConference {
                    id: "2".to_string(),
                    name: "test".to_string(),
                    talks: None,
                    city: None
                })
            };
            let query_key = &operation.meta.query_key;

            if query_key == &1 {
                make_result::<Q>(operation, Box::new(data_one))
            } else if query_key == &2 {
                make_result::<Q>(operation, Box::new(data_unrelated))
            } else {
                panic!("Received unexpected query with key {}", query_key);
            }
        }
    }

    let variables = Variables {
        id: "1".to_string()
    };
    let variables_unrelated = Variables {
        id: "2".to_string()
    };
    let operation_one = make_op_with_key(GetConference, variables, 1);
    let operation_unrelated = make_op_with_key(GetConference, variables_unrelated, 2);

    let client = DummyClient {
        tracker: tracker.clone()
    };
    let exchange = NormalizedCacheExchange::new().build(Fetch(tracker.clone()));

    let res = exchange
        .run::<GetConference, _>(operation_one.clone(), client.clone())
        .await;
    assert!(res.is_ok());

    let res = exchange
        .run::<GetConference, _>(operation_unrelated.clone(), client.clone())
        .await;
    assert!(res.is_ok());

    tracker.assert_that("Client::rerun_query").wasnt_called();
}

#[tokio::test]
async fn writes_optimistic_mutations_to_the_cache() {
    let tracker = Tracker::new();

    struct Fetch(Arc<Tracker>);

    #[track_with(0)]
    #[async_trait]
    impl Exchange for Fetch {
        async fn run<Q: GraphQLQuery, C: Client>(
            &self,
            operation: Operation<Q::Variables>,
            _client: C
        ) -> ExchangeResult<Q::ResponseData> {
            let data_one = ResponseData {
                conference: Some(GetConferenceConference {
                    id: "1".to_string(),
                    name: "test".to_string(),
                    talks: None,
                    city: None
                })
            };
            let data_mutation = add_conference::ResponseData {
                add_conference: Some(AddConferenceAddConference {
                    id: "1".to_string(),
                    name: "test3".to_string(),
                    talks: None,
                    city: None
                })
            };

            let query_key = &operation.meta.query_key;

            if query_key == &1 {
                make_result::<Q>(operation, Box::new(data_one))
            } else if query_key == &2 {
                make_result::<Q>(operation, Box::new(data_mutation))
            } else {
                panic!("Received unexpected query with key {}", query_key);
            }
        }
    }

    #[track_with(tracker)]
    let optimistic = || {
        Some(add_conference::ResponseData {
            add_conference: Some(AddConferenceAddConference {
                id: "1".to_string(),
                name: "test3".to_string(),
                talks: None,
                city: None
            })
        })
    };

    let client = DummyClient {
        tracker: tracker.clone()
    };
    let exchange = NormalizedCacheExchange::new().build(Fetch(tracker.clone()));

    let op_one = make_op_with_key(
        GetConference,
        Variables {
            id: "1".to_string()
        },
        1
    );
    let op_mut = {
        let variables = add_conference::Variables {
            name: "test3".to_string(),
            city: None
        };
        let (query, meta) = <AddConference as GraphQLQuery>::build_query(variables);
        let extension =
            NormalizedCacheExtension::new().optimistic_result::<AddConference, _>(optimistic);
        Operation {
            key: 2,
            query,
            meta: OperationMeta {
                query_key: 2,
                ..meta
            },
            options: OperationOptions {
                url: "http://0.0.0.0".parse().unwrap(),
                request_policy: RequestPolicy::CacheFirst,
                extra_headers: None,
                extensions: Some(artemis::ext![extension])
            }
        }
    };

    let res = exchange
        .run::<GetConference, _>(op_one.clone(), client.clone())
        .await;
    assert!(res.is_ok());

    let res = exchange
        .run::<AddConference, _>(op_mut.clone(), client.clone())
        .await;
    assert!(res.is_ok());
    tracker.assert_that("optimistic").was_called_once();
    tracker
        .assert_that("Client::rerun_query")
        .was_called_times(2)
        .with((1u64))
        .not_with((2u64));
    tracker.assert_that("Fetch::run").was_called_times(2);
}

#[tokio::test]
async fn correctly_clears_on_error() {
    TRACKER.clear();
    let tracker = Tracker::new();

    #[track_with(TRACKER, namespace = "clear_on_error")]
    fn optimistic() -> Option<add_conference::ResponseData> {
        Some(add_conference::ResponseData {
            add_conference: Some(AddConferenceAddConference {
                id: "asd".to_string(),
                name: "test3".to_string(),
                talks: None,
                city: None
            })
        })
    }

    #[track_with(TRACKER, namespace = "clear_on_error")]
    fn update(
        data: &Option<add_conference::ResponseData>,
        store: QueryStore,
        dependencies: &mut HashSet<String>
    ) {
        println!("Update Data: {:?}", data);
        if let Some(conference) = data.as_ref().and_then(|data| data.add_conference.as_ref()) {
            store.update_query(
                GetConferences,
                get_conferences::Variables,
                |current_data| {
                    let result = if let Some(current_data) = current_data {
                        Some(get_conferences::ResponseData {
                            conferences: current_data.conferences.map(|vec| {
                                let mut vec: Vec<_> = vec.iter().cloned().collect();
                                vec.push(GetConferencesConferences {
                                    id: conference.id.clone(),
                                    name: conference.name.clone()
                                });
                                vec
                            })
                        })
                    } else {
                        None
                    };
                    result
                },
                dependencies
            );
        } else {
            store.update_query(
                GetConferences,
                get_conferences::Variables,
                |current_data| {
                    if current_data.is_some() {
                        Some(get_conferences::ResponseData {
                            conferences: Some(Vec::new())
                        })
                    } else {
                        None
                    }
                },
                dependencies
            );
        }
    }

    let operation_one = make_op(GetConferences, get_conferences::Variables);
    let variables_mutation = add_conference::Variables {
        name: "test2".to_string(),
        city: None
    };
    let operation_mutation = {
        let (query, meta) = <AddConference as GraphQLQuery>::build_query(variables_mutation);
        let extension = NormalizedCacheExtension::new()
            .optimistic_result::<AddConference, _>(optimistic)
            .update::<AddConference, _>(update);
        Operation {
            key: 2,
            query,
            meta: OperationMeta {
                query_key: 2,
                ..meta
            },
            options: OperationOptions {
                url: "http://0.0.0.0".parse().unwrap(),
                request_policy: RequestPolicy::CacheFirst,
                extra_headers: None,
                extensions: Some(artemis::ext![extension])
            }
        }
    };

    struct Fetch(Arc<Tracker>);

    #[track_with(0)]
    #[async_trait]
    impl Exchange for Fetch {
        async fn run<Q: GraphQLQuery, C: Client>(
            &self,
            operation: Operation<Q::Variables>,
            _client: C
        ) -> ExchangeResult<Q::ResponseData> {
            let data_one = get_conferences::ResponseData {
                conferences: Some(vec![GetConferencesConferences {
                    id: "1".to_string(),
                    name: "test".to_string()
                }])
            };

            let query_key = &operation.meta.query_key;

            if query_key == &2 {
                Ok(OperationResult {
                    key: operation.key,
                    meta: operation.meta,
                    response: Response {
                        data: None,
                        errors: Some(vec![Error {
                            path: None,
                            extensions: None,
                            locations: None,
                            message: "Test error".to_string()
                        }]),
                        debug_info: None
                    }
                })
            } else {
                make_result::<Q>(operation, Box::new(data_one))
            }
        }
    }

    let client = DummyClient {
        tracker: tracker.clone()
    };
    let exchange = NormalizedCacheExchange::new().build(Fetch(tracker.clone()));

    let res = exchange
        .run::<GetConferences, _>(operation_one.clone(), client.clone())
        .await;
    assert!(res.is_ok());
    let res = exchange
        .run::<AddConference, _>(operation_mutation.clone(), client.clone())
        .await;
    assert!(res.is_ok());
    TRACKER
        .assert_that("clear_on_error::optimistic")
        .was_called_once();
    TRACKER
        .assert_that("clear_on_error::update")
        .was_called_times(2);
    tracker
        .assert_that("Client::rerun_query")
        .was_called_times(2);
}

#[tokio::test]
async fn follows_optimistic_on_initial_write() {
    let tracker = Tracker::new();

    let client = DummyClient {
        tracker: tracker.clone()
    };
    let mut op_one = make_op_with_key(
        GetConference,
        Variables {
            id: "1".to_string()
        },
        1
    );

    struct Fetch(Arc<Tracker>);

    #[track_with(0)]
    #[async_trait]
    impl Exchange for Fetch {
        async fn run<Q: GraphQLQuery, C: Client>(
            &self,
            operation: Operation<Q::Variables>,
            _client: C
        ) -> ExchangeResult<Q::ResponseData> {
            let data_one = ResponseData {
                conference: Some(GetConferenceConference {
                    id: "1".to_string(),
                    name: "test".to_string(),
                    talks: None,
                    city: None
                })
            };

            if operation.key == 1 {
                make_result::<Q>(operation, Box::new(data_one))
            } else {
                unreachable!()
            }
        }
    }

    let optimistic_data = ResponseData {
        conference: Some(GetConferenceConference {
            id: "1".to_string(),
            name: "other_test_name".to_string(),
            talks: None,
            city: None
        })
    };

    #[track_with(tracker)]
    let optimistic = || {
        Some(ResponseData {
            conference: Some(GetConferenceConference {
                id: "1".to_string(),
                name: "other_test_name".to_string(),
                talks: None,
                city: None
            })
        })
    };

    let exchange = NormalizedCacheExchange::new().build(Fetch(tracker.clone()));
    let extension =
        NormalizedCacheExtension::new().optimistic_result::<GetConference, _>(optimistic);
    op_one.options.extensions = Some(artemis::ext![extension]);

    let res = exchange
        .run::<GetConference, _>(op_one.clone(), client)
        .await;
    assert!(res.is_ok());
    let data: ResponseData = res.unwrap().response.data.unwrap();
    assert_eq!(&data.conference.unwrap().name, "test");
    tracker.assert_that("optimistic").was_called_once();

    let push_data: (u64, ExchangeResult<ResponseData>) = (
        1u64,
        Ok(OperationResult {
            key: 1,
            meta: op_one.meta,
            response: Response {
                data: Some(optimistic_data),
                errors: None,
                debug_info: None
            }
        })
    );

    tracker
        .assert_that("Client::push_result")
        .was_called_once()
        .with(push_data);
}