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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
use std::collections::VecDeque;
use std::future::Future;
use std::{marker::PhantomData, sync::Arc};
use futures::future::try_join_all;
use futures::stream::{try_unfold, SelectAll};
use futures::TryStream;
use serde::{de::DeserializeOwned, Serialize};
use crate::dto::items::*;
use crate::{
ApiClient, CondBoxedStream, CondSend, EqIdentity, Filter, Identity, IntoParams, IntoPatch,
Partition, Patch, Result, Search, SetCursor, UpsertOptions, WithPartition,
};
use super::utils::{get_duplicates_from_result, get_missing_from_result};
/// A resource instance contains methods for accessing a single
/// CDF resource type.
pub struct Resource<T> {
/// A reference to the shared API Client.
pub api_client: Arc<ApiClient>,
marker: PhantomData<T>,
}
impl<T> Resource<T> {
/// Create a new resource with given API client.
///
/// # Arguments
///
/// * `api_client` - API client reference.
pub fn new(api_client: Arc<ApiClient>) -> Self {
Resource {
api_client,
marker: PhantomData,
}
}
}
impl<T> Clone for Resource<T> {
fn clone(&self) -> Self {
Self {
api_client: self.api_client.clone(),
marker: PhantomData,
}
}
}
impl<T> WithApiClient for Resource<T> {
fn get_client(&self) -> &ApiClient {
&self.api_client
}
}
/// Trait for a type that contains an API client.
pub trait WithApiClient {
/// Get the API client for this type.
fn get_client(&self) -> &ApiClient;
}
/// Trait for a type with a base path.
pub trait WithBasePath {
/// Base path for this resource type.
const BASE_PATH: &'static str;
}
/// Trait for simple GET / endpoints.
pub trait List<TParams, TResponse>
where
TParams: IntoParams + Send + Sync + 'static,
TResponse: Serialize + DeserializeOwned + Send + Sync,
Self: WithApiClient + WithBasePath + Sync,
{
/// Query a resource with optional query parameters.
///
/// # Arguments
///
/// * `params` - Query parameters.
fn list(
&self,
params: Option<TParams>,
) -> impl Future<Output = Result<ItemsVec<TResponse, Cursor>>> + CondSend {
async move {
self.get_client()
.get_with_params(Self::BASE_PATH, params)
.await
}
}
/// Query a resource with query parameters, continuing until the cursor is exhausted.
///
/// # Arguments
///
/// * `params` - Initial query parameters. This can contain a cursor which is the starting point.
fn list_all(
&self,
mut params: TParams,
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend
where
TParams: SetCursor + Clone,
TResponse: Send,
{
async move {
let mut result = vec![];
loop {
let lparams = params.clone();
let response: ItemsVec<TResponse, Cursor> = self
.get_client()
.get_with_params(Self::BASE_PATH, Some(lparams))
.await?;
for it in response.items {
result.push(it);
}
match response.extra_fields.next_cursor {
Some(cursor) => params.set_cursor(Some(cursor)),
None => return Ok(result),
}
}
}
}
/// List resources, following cursors. This returns a stream, you can abort the stream whenever you
/// want and only resources retrieved up to that point will be returned.
///
/// Each item in the stream will be a result, after the first error is returned the
/// stream will end.
///
/// # Arguments
///
/// * `params` - Initial query parameters. This can contain a cursors used as starting point.
fn list_all_stream(
&self,
params: TParams,
) -> impl TryStream<Ok = TResponse, Error = crate::Error, Item = Result<TResponse>> + CondSend
where
TParams: SetCursor + Clone,
TResponse: Send + 'static,
{
let state = CursorStreamState {
req: params,
responses: VecDeque::new(),
next_cursor: CursorState::Initial,
};
try_unfold(state, move |mut state| async move {
if let Some(next) = state.responses.pop_front() {
Ok(Some((next, state)))
} else {
let cursor = match std::mem::take(&mut state.next_cursor) {
CursorState::Initial => None,
CursorState::Some(x) => Some(x),
CursorState::End => {
return Ok(None);
}
};
state.req.set_cursor(cursor);
let response: ItemsVec<TResponse, Cursor> = self
.get_client()
.get_with_params(Self::BASE_PATH, Some(state.req.clone()))
.await?;
state.responses.extend(response.items);
state.next_cursor = match response.extra_fields.next_cursor {
Some(x) => CursorState::Some(x),
None => CursorState::End,
};
if let Some(next) = state.responses.pop_front() {
Ok(Some((next, state)))
} else {
Ok(None)
}
}
})
}
}
/// Trait for creating resources with POST / requests.
pub trait Create<TCreate, TResponse>
where
TCreate: Serialize + Sync + Send,
TResponse: Serialize + DeserializeOwned + Send,
Self: WithApiClient + WithBasePath + Sync,
{
/// Create a list of resources.
///
/// # Arguments
///
/// `creates` - List of resources to create.
fn create(
&self,
creates: &[TCreate],
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend {
async move {
let items = Items::new(creates);
let response: ItemsVec<TResponse> =
self.get_client().post(Self::BASE_PATH, &items).await?;
Ok(response.items)
}
}
/// Create a list of resources, converting from a different type.
///
/// # Arguments
///
/// * `creates` - List of resources to create.
fn create_from(
&self,
creates: &[impl Into<TCreate> + Sync + Clone],
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend {
async move {
let to_add: Vec<TCreate> = creates.iter().map(|i| i.clone().into()).collect();
self.create(&to_add).await
}
}
/// Create a list of resources, ignoring any that fail with general "conflict" errors.
///
/// # Arguments
///
/// * `creates` - List of resources to create.
fn create_ignore_duplicates(
&self,
creates: &[TCreate],
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend
where
TCreate: EqIdentity,
{
async move {
let resp = self.create(creates).await;
let duplicates: Option<Vec<Identity>> = get_duplicates_from_result(&resp);
if let Some(duplicates) = duplicates {
let next: Vec<&TCreate> = creates
.iter()
.filter(|c| !duplicates.iter().any(|i| c.eq(i)))
.collect();
if next.is_empty() {
if duplicates.len() == creates.len() {
return Ok(vec![]);
}
return resp;
}
let items = Items::new(next);
let response: ItemsVec<TResponse> =
self.get_client().post(Self::BASE_PATH, &items).await?;
Ok(response.items)
} else {
resp
}
}
}
/// Create a list of resources, converting from a different type, and ignoring any that fail
/// with general "conflict" errors.
///
/// # Arguments
///
/// * `creates` - List of resources to create.
fn create_from_ignore_duplicates<'a, T: 'a>(
&self,
creates: &'a [impl Into<TCreate> + Sync + Clone],
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend
where
TCreate: EqIdentity,
{
async move {
let to_add: Vec<TCreate> = creates.iter().map(|i| i.clone().into()).collect();
self.create_ignore_duplicates(&to_add).await
}
}
}
/// Trait for upserts of resources that support both Create and Update.
pub trait Upsert<'a, TCreate, TUpdate, TResponse>
where
TCreate: Serialize + Sync + Send + EqIdentity + 'a + Clone + IntoPatch<TUpdate>,
TUpdate: Serialize + Sync + Send + Default,
TResponse: Serialize + DeserializeOwned + Sync + Send,
Self: WithApiClient + WithBasePath + Sync,
{
/// Upsert a list resources, meaning that they will first be attempted created,
/// and if that fails with a conflict, update any that already existed, and create
/// the remainder.
///
/// # Arguments
///
/// * `upserts` - Resources to insert or update.
/// * `options` - Configuration for upserts, which fields are kept and which are overwritten.
fn upsert(
&'a self,
upserts: &'a [TCreate],
options: &UpsertOptions,
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend {
async move {
let items = Items::new(upserts);
let resp: Result<ItemsVec<TResponse>> =
self.get_client().post(Self::BASE_PATH, &items).await;
let duplicates: Option<Vec<Identity>> = get_duplicates_from_result(&resp);
if let Some(duplicates) = duplicates {
let mut to_create = Vec::with_capacity(upserts.len() - duplicates.len());
let mut to_update = Vec::with_capacity(duplicates.len());
for it in upserts {
let idt = duplicates.iter().find(|i| it.eq(i));
if let Some(idt) = idt {
to_update.push(Patch::<TUpdate> {
id: idt.clone(),
update: it.clone().patch(options),
});
} else {
to_create.push(it);
}
}
let mut result = Vec::with_capacity(to_create.len() + to_update.len());
if !to_create.is_empty() {
let mut create_response: ItemsVec<TResponse> = self
.get_client()
.post(Self::BASE_PATH, &Items::new(to_create))
.await?;
result.append(&mut create_response.items);
}
if !to_update.is_empty() {
let mut update_response: ItemsVec<TResponse> = self
.get_client()
.post(
&format!("{}/update", Self::BASE_PATH),
&Items::new(&to_update),
)
.await?;
result.append(&mut update_response.items);
}
Ok(result)
} else {
resp.map(|i| i.items)
}
}
}
}
impl<'a, T, TCreate, TUpdate, TResponse> Upsert<'a, TCreate, TUpdate, TResponse> for T
where
T: Create<TCreate, TResponse> + Update<Patch<TUpdate>, TResponse> + Sync,
TCreate: Serialize + Sync + Send + EqIdentity + 'a + Clone + IntoPatch<TUpdate>,
TUpdate: Serialize + Sync + Send + Default,
TResponse: Serialize + DeserializeOwned + Sync + Send,
{
}
/// Trait for resource types that support upserts directly.
pub trait UpsertCollection<TUpsert, TResponse> {
/// Upsert a list of resources.
///
/// # Arguments
///
/// * `collection` - Items to insert or update.
fn upsert(
&self,
collection: &TUpsert,
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend
where
TUpsert: Serialize + Sync + Send,
TResponse: Serialize + DeserializeOwned + Sync + Send,
Self: WithApiClient + WithBasePath + Sync,
{
async move {
let response: ItemsVec<TResponse> =
self.get_client().post(Self::BASE_PATH, &collection).await?;
Ok(response.items)
}
}
}
/// Trait for resource types that can be deleted with a list of `TIdt`.
pub trait Delete<TIdt>
where
TIdt: Serialize + Sync + Send,
Self: WithApiClient + WithBasePath + Sync,
{
/// Delete a list of resources by ID.
///
/// # Arguments
///
/// * `deletes` - IDs of items to delete.
fn delete(&self, deletes: &[TIdt]) -> impl Future<Output = Result<()>> + CondSend {
async move {
let items = Items::new(deletes);
self.get_client()
.post::<::serde_json::Value, Items<&[TIdt]>>(
&format!("{}/delete", Self::BASE_PATH),
&items,
)
.await?;
Ok(())
}
}
}
/// Trait for resource types that can be deleted with a more complex request.
pub trait DeleteWithRequest<TReq>
where
TReq: Serialize + Sync + Send,
Self: WithApiClient + WithBasePath + Sync,
{
/// Delete resources using `req`.
///
/// # Arguments
///
/// * `req` - Request describing items to delete.
fn delete(&self, req: &TReq) -> impl Future<Output = Result<()>> + CondSend {
async move {
self.get_client()
.post::<::serde_json::Value, TReq>(&format!("{}/delete", Self::BASE_PATH), req)
.await?;
Ok(())
}
}
}
/// Trait for resource types that can be deleted with a list of identities and
/// a boolean option to ignore unknown ids.
pub trait DeleteWithIgnoreUnknownIds<TIdt>
where
TIdt: Serialize + Sync + Send,
Self: WithApiClient + WithBasePath + Sync,
{
/// Delete a list of resources, optionally ignore unknown ids.
///
/// # Arguments
///
/// * `deletes` - IDs of items to delete.
/// * `ignore_unknown_ids` - If `true`, missing IDs will be ignored, and not
/// cause the request to fail.
fn delete(
&self,
deletes: impl Into<TIdt> + Send,
ignore_unknown_ids: bool,
) -> impl Future<Output = Result<()>> + CondSend
where
Self: Sync,
{
async move {
let req = Items::new_with_extra_fields(
deletes.into(),
IgnoreUnknownIds { ignore_unknown_ids },
);
self.get_client()
.post::<::serde_json::Value, _>(&format!("{}/delete", Self::BASE_PATH), &req)
.await?;
Ok(())
}
}
}
/// Trait for resource types that can be deleted, and where the delete request
/// has a non-empty response.
pub trait DeleteWithResponse<TIdt, TResponse>
where
TIdt: Serialize + Sync + Send,
TResponse: Serialize + DeserializeOwned + Sync + Send,
Self: WithApiClient + WithBasePath + Sync,
{
/// Delete a list of resources.
///
/// # Arguments
///
/// * `deletes` - IDs of items to delete.
fn delete(
&self,
deletes: &[TIdt],
) -> impl Future<Output = Result<ItemsVec<TResponse>>> + CondSend {
async move {
let items = Items::new(deletes);
let response: ItemsVec<TResponse> = self
.get_client()
.post(&format!("{}/delete", Self::BASE_PATH), &items)
.await?;
Ok(response)
}
}
}
/// Trait for resource types that can be patch updated.
pub trait Update<TUpdate, TResponse>
where
TUpdate: Serialize + Sync + Send,
TResponse: Serialize + DeserializeOwned,
Self: WithApiClient + WithBasePath + Sync,
{
/// Update a list of resources.
///
/// # Arguments
///
/// * `updates` - Items to update.
fn update(
&self,
updates: &[TUpdate],
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend {
async move {
let items = Items::new(updates);
let response: ItemsVec<TResponse> = self
.get_client()
.post(&format!("{}/update", Self::BASE_PATH), &items)
.await?;
Ok(response.items)
}
}
/// Update a list of resources by converting to the update from a different type.
///
/// # Arguments
///
/// * `updates` - Items to update.
fn update_from<'a, T>(
&self,
updates: &'a [T],
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend
where
T: std::marker::Sync + Clone + 'a,
TUpdate: From<T>,
{
async move {
let to_update: Vec<TUpdate> =
updates.iter().map(|i| TUpdate::from(i.clone())).collect();
self.update(&to_update).await
}
}
/// Update a list of resources, ignoring any that fail due to items missing in CDF.
///
/// # Arguments
///
/// * `updates` - Items to update.
fn update_ignore_unknown_ids(
&self,
updates: &[TUpdate],
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend
where
TUpdate: EqIdentity,
TResponse: Send,
{
async move {
let response = self.update(updates).await;
let missing: Option<Vec<Identity>> = get_missing_from_result(&response);
if let Some(missing) = missing {
let next: Vec<&TUpdate> = updates
.iter()
.filter(|c| !missing.iter().any(|i| c.eq(i)))
.collect();
if next.is_empty() {
if missing.len() == updates.len() {
return Ok(vec![]);
}
return response;
}
let items = Items::new(next);
let response: ItemsVec<TResponse> = self
.get_client()
.post(&format!("{}/update", Self::BASE_PATH), &items)
.await?;
Ok(response.items)
} else {
response
}
}
}
/// Update a list of resources by converting from a different type, ignoring any that fail
/// due items missing in CDF.
///
/// # Arguments
///
/// * `updates` - Items to update.
fn update_from_ignore_unknown_ids<'a, T>(
&self,
updates: &'a [T],
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend
where
T: Sync + Clone + 'a,
TUpdate: From<T> + EqIdentity,
TResponse: Send,
{
async move {
let to_update: Vec<TUpdate> =
updates.iter().map(|i| TUpdate::from(i.clone())).collect();
self.update_ignore_unknown_ids(&to_update).await
}
}
}
/// Trait for retrieving items from CDF by id.
pub trait Retrieve<TIdt, TResponse>
where
TIdt: Serialize + Sync + Send,
TResponse: Serialize + DeserializeOwned,
Self: WithApiClient + WithBasePath + Sync,
{
/// Retrieve a list of items from CDF by id.
///
/// # Arguments
///
/// * `ids` - IDs of items to retrieve.
fn retrieve(&self, ids: &[TIdt]) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend {
async move {
let items = Items::new(ids);
let response: ItemsVec<TResponse> = self
.get_client()
.post(&format!("{}/byids", Self::BASE_PATH), &items)
.await?;
Ok(response.items)
}
}
}
/// Trait for retrieving items from CDF with a more complex request type.
pub trait RetrieveWithRequest<TRequest, TResponse>
where
TRequest: Serialize + Sync + Send,
TResponse: Serialize + DeserializeOwned,
Self: WithApiClient + WithBasePath + Sync,
{
/// Retrieve items from CDF with a more complex request.
///
/// # Arguments
///
/// * `req` - Request describing items to retrieve.
fn retrieve(&self, req: &TRequest) -> impl Future<Output = Result<TResponse>> + CondSend {
async move {
let response: TResponse = self
.get_client()
.post(&format!("{}/byids", Self::BASE_PATH), req)
.await?;
Ok(response)
}
}
}
/// Trait for retrieving items from CDF with an option to ignore unknown IDs.
pub trait RetrieveWithIgnoreUnknownIds<TIdt, TResponse>
where
TIdt: Serialize + Sync + Send,
TResponse: Serialize + DeserializeOwned,
Self: WithApiClient + WithBasePath + Sync,
{
/// Retrieve a list of items from CDF. If ignore_unknown_ids is false,
/// this will fail if any items are missing from CDF.
///
/// # Arguments
///
/// * `ids` - IDs of items to retrieve.
/// * `ignore_unknown_ids` - If `true`, items missing from CDF will be ignored, and not
/// cause the request to fail.
fn retrieve(
&self,
ids: impl Into<TIdt> + Send,
ignore_unknown_ids: bool,
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend {
async move {
let items =
Items::new_with_extra_fields(ids.into(), IgnoreUnknownIds { ignore_unknown_ids });
let response: ItemsVec<TResponse> = self
.get_client()
.post(&format!("{}/byids", Self::BASE_PATH), &items)
.await?;
Ok(response.items)
}
}
}
/// Trait for resource types that allow filtering with a simple filter.
pub trait FilterItems<TFilter, TResponse>
where
TFilter: Serialize + Sync + Send + 'static,
TResponse: Serialize + DeserializeOwned,
Self: WithApiClient + WithBasePath + Sync,
{
/// Filter resources using a simple filter.
/// The response may contain a cursor that can be used to paginate results.
///
/// # Arguments
///
/// * `filter` - Filter which items to retrieve.
/// * `cursor` - Optional cursor for pagination.
/// * `limit` - Maximum number of result items.
fn filter_items(
&self,
filter: TFilter,
cursor: Option<String>,
limit: Option<u32>,
) -> impl Future<Output = Result<ItemsVec<TResponse, Cursor>>> + CondSend {
async move {
let filter = Filter::<TFilter>::new(filter, cursor, limit);
let response: ItemsVec<TResponse, Cursor> = self
.get_client()
.post(&format!("{}/list", Self::BASE_PATH), &filter)
.await?;
Ok(response)
}
}
}
impl<TFilter, TResponse, T> FilterWithRequest<Filter<TFilter>, TResponse> for T
where
TFilter: Serialize + Sync + Send + 'static,
TResponse: Serialize + DeserializeOwned,
T: FilterItems<TFilter, TResponse>,
Self: WithApiClient + WithBasePath,
{
}
#[derive(Debug, Default)]
pub(crate) enum CursorState {
Initial,
Some(String),
#[default]
End,
}
pub(crate) struct CursorStreamState<TFilter, TResponse> {
pub(crate) req: TFilter,
pub(crate) responses: VecDeque<TResponse>,
pub(crate) next_cursor: CursorState,
}
/// Trait for resource types that allow filtering with a more complex request.
pub trait FilterWithRequest<TFilter, TResponse>
where
TFilter: Serialize + Sync + Send + 'static,
TResponse: Serialize + DeserializeOwned,
Self: WithApiClient + WithBasePath + Sync,
{
/// Filter resources.
///
/// # Arguments
///
/// * `filter` - Filter which items to retrieve.
fn filter(
&self,
filter: TFilter,
) -> impl Future<Output = Result<ItemsVec<TResponse, Cursor>>> + CondSend {
async move {
let response: ItemsVec<TResponse, Cursor> = self
.get_client()
.post(&format!("{}/list", Self::BASE_PATH), &filter)
.await?;
Ok(response)
}
}
/// Filter resources, following cursors until they are exhausted.
///
/// # Arguments
///
/// * `filter` - Filter which items to retrieve.
fn filter_all(
&self,
mut filter: TFilter,
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend
where
TFilter: SetCursor,
TResponse: Send,
{
async move {
let mut result = vec![];
loop {
let response: ItemsVec<TResponse, Cursor> = self
.get_client()
.post(&format!("{}/list", Self::BASE_PATH), &filter)
.await?;
for it in response.items {
result.push(it);
}
match response.extra_fields.next_cursor {
Some(cursor) => filter.set_cursor(Some(cursor)),
None => return Ok(result),
}
}
}
}
/// Filter resources, following cursors. This returns a stream, you can abort the stream whenever you
/// want and only resources retrieved up to that point will be returned.
///
/// Each item in the stream will be a result, after the first error is returned the
/// stream will end.
///
/// # Arguments
///
/// * `filter` - Filter which items to retrieve.
fn filter_all_stream(
&self,
filter: TFilter,
) -> impl TryStream<Ok = TResponse, Error = crate::Error, Item = Result<TResponse>> + CondSend
where
TFilter: SetCursor,
TResponse: Send + 'static,
{
let state = CursorStreamState {
req: filter,
responses: VecDeque::new(),
next_cursor: CursorState::Initial,
};
try_unfold(state, move |mut state| async move {
if let Some(next) = state.responses.pop_front() {
Ok(Some((next, state)))
} else {
let cursor = match std::mem::take(&mut state.next_cursor) {
CursorState::Initial => None,
CursorState::Some(x) => Some(x),
CursorState::End => {
return Ok(None);
}
};
state.req.set_cursor(cursor);
let response: ItemsVec<TResponse, Cursor> = self
.get_client()
.post(&format!("{}/list", Self::BASE_PATH), &state.req)
.await?;
state.responses.extend(response.items);
state.next_cursor = match response.extra_fields.next_cursor {
Some(x) => CursorState::Some(x),
None => CursorState::End,
};
if let Some(next) = state.responses.pop_front() {
Ok(Some((next, state)))
} else {
Ok(None)
}
}
})
}
/// Filter resources using partitioned reads, following cursors until all partitions are
/// exhausted.
///
/// # Arguments
///
/// * `filter` - Filter which items to retrieve.
/// * `num_partitions` - Number of partitions.
fn filter_all_partitioned(
&self,
filter: TFilter,
num_partitions: u32,
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend
where
TFilter: SetCursor + WithPartition,
TResponse: Send,
{
async move {
let mut futures = Vec::with_capacity(num_partitions as usize);
for partition in 0..num_partitions {
let part_filter =
filter.with_partition(Partition::new(partition + 1, num_partitions));
futures.push(self.filter_all(part_filter));
}
let results = try_join_all(futures).await?;
let mut response_items = Vec::with_capacity(results.iter().map(|i| i.len()).sum());
for chunk in results.into_iter() {
response_items.extend(chunk);
}
Ok(response_items)
}
}
/// Filter resources using partitioned reads, following cursors until all partitions
/// are exhausted. This returns a stream.
///
/// Note that the returned stream is simply a combinator of streams returned by
/// `filter_all_stream` for different partitions.
///
/// The order of the returned values is not guaranteed to be in any way consistent.
///
/// # Arguments
///
/// * `filter` - Filter which items to retrieve.
/// * `num_partitions` - Number of partitions.
fn filter_all_partitioned_stream(
&self,
filter: TFilter,
num_partitions: u32,
) -> impl TryStream<Ok = TResponse, Error = crate::Error, Item = Result<TResponse>> + CondSend
where
TFilter: SetCursor + WithPartition,
TResponse: Send + 'static,
{
let mut streams = SelectAll::new();
for partition in 0..num_partitions {
let part_filter = filter.with_partition(Partition::new(partition + 1, num_partitions));
streams.push(self.filter_all_stream(part_filter).boxed_cond());
}
streams
}
}
/// Trait for resource types that allow filtering with fuzzy search.
pub trait SearchItems<'a, TFilter, TSearch, TResponse>
where
TFilter: Serialize + Sync + Send + 'a,
TSearch: Serialize + Sync + Send + 'a,
TResponse: Serialize + DeserializeOwned,
Self: WithApiClient + WithBasePath + Sync,
{
/// Fuzzy search resources.
///
/// # Arguments
///
/// * `filter` - Simple filter applied to items.
/// * `search` - Fuzzy search.
/// * `limit` - Maximum number of items to retrieve.
fn search(
&'a self,
filter: TFilter,
search: TSearch,
limit: Option<u32>,
) -> impl Future<Output = Result<Vec<TResponse>>> + CondSend {
async move {
let req = Search::<TFilter, TSearch>::new(filter, search, limit);
let response: ItemsVec<TResponse> = self
.get_client()
.post(&format!("{}/search", Self::BASE_PATH), &req)
.await?;
Ok(response.items)
}
}
}