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
use std::fmt::{self, Debug, Formatter};
use std::future::Future;
use std::marker::PhantomData;
use crate::provider::{future, ProvideCredentials};
#[derive(Copy, Clone)]
pub struct ProvideCredentialsFn<'c, T> {
f: T,
phantom: PhantomData<&'c T>,
}
impl<T> Debug for ProvideCredentialsFn<'_, T> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "ProvideCredentialsFn")
}
}
impl<'c, T, F> ProvideCredentials for ProvideCredentialsFn<'c, T>
where
T: Fn() -> F + Send + Sync + 'c,
F: Future<Output = crate::provider::Result> + Send + 'static,
{
fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>
where
Self: 'a,
{
future::ProvideCredentials::new((self.f)())
}
}
pub fn provide_credentials_fn<'c, T, F>(f: T) -> ProvideCredentialsFn<'c, T>
where
T: Fn() -> F + Send + Sync + 'c,
F: Future<Output = crate::provider::Result> + Send + 'static,
{
ProvideCredentialsFn {
f,
phantom: Default::default(),
}
}
#[cfg(test)]
mod test {
use crate::credential_fn::provide_credentials_fn;
use crate::{
provider::{future, ProvideCredentials},
Credentials,
};
use async_trait::async_trait;
use std::fmt::{Debug, Formatter};
fn assert_send_sync<T: Send + Sync>() {}
#[test]
fn creds_are_send_sync() {
assert_send_sync::<Credentials>()
}
#[async_trait]
trait AnotherTrait: Send + Sync {
async fn creds(&self) -> Credentials;
}
struct AnotherTraitWrapper<T> {
inner: T,
}
impl<T> Debug for AnotherTraitWrapper<T> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "wrapper")
}
}
impl<T: AnotherTrait> ProvideCredentials for AnotherTraitWrapper<T> {
fn provide_credentials<'a>(&'a self) -> future::ProvideCredentials<'a>
where
Self: 'a,
{
future::ProvideCredentials::new(async move { Ok(self.inner.creds().await) })
}
}
#[tokio::test]
async fn provide_credentials_fn_closure_can_borrow() {
fn check_is_str_ref(_input: &str) {}
async fn test_async_provider(input: String) -> crate::provider::Result {
Ok(Credentials::new(&input, &input, None, None, "test"))
}
let things_to_borrow = vec!["one".to_string(), "two".to_string()];
let mut providers = Vec::new();
for thing in &things_to_borrow {
let provider = provide_credentials_fn(move || {
check_is_str_ref(thing);
test_async_provider(thing.into())
});
providers.push(provider);
}
let (two, one) = (providers.pop().unwrap(), providers.pop().unwrap());
assert_eq!(
"one",
one.provide_credentials().await.unwrap().access_key_id()
);
assert_eq!(
"two",
two.provide_credentials().await.unwrap().access_key_id()
);
}
}