-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
Copy pathlib.rs
259 lines (221 loc) · 7.58 KB
/
lib.rs
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
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use async_trait::async_trait;
use aws_credential_types::{cache::CredentialsCache, provider::ProvideCredentials, Credentials};
use aws_sdk_lambda::{Client, Region, PKG_VERSION};
use aws_smithy_async::rt::sleep::{AsyncSleep, Sleep};
use aws_smithy_client::erase::DynConnector;
use aws_smithy_http::{body::SdkBody, result::ConnectorError};
use wasm_bindgen::{prelude::*, JsCast};
macro_rules! log {
( $( $t:tt )* ) => {
web_sys::console::log_1(&format!( $( $t )* ).into());
}
}
#[wasm_bindgen(module = "env")]
extern "C" {
fn now() -> f64;
}
#[wasm_bindgen(start)]
pub fn start() {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
log!("initializing module...");
}
#[wasm_bindgen]
pub async fn main(region: String, verbose: bool) -> Result<String, String> {
log!("");
if verbose {
log!("Lambda client version: {}", PKG_VERSION);
log!("Region: {}", region);
log!("");
}
let credentials_provider = static_credential_provider();
let credentials = credentials_provider.provide_credentials().await.unwrap();
let access_key = credentials.access_key_id();
let shared_config = aws_config::from_env()
.sleep_impl(BrowserSleep)
.region(Region::new(region))
.credentials_cache(browser_credentials_cache())
.credentials_provider(credentials_provider)
.http_connector(DynConnector::new(Adapter::new(
verbose,
access_key == "access_key",
)))
.load()
.await;
let client = Client::new(&shared_config);
let now = std::time::Duration::new(now() as u64, 0);
log!("current date in unix timestamp: {}", now.as_secs());
let resp = client
.list_functions()
.send()
.await
.map_err(|e| format!("{:?}", e))?;
let functions = resp.functions().unwrap_or_default();
for function in functions {
log!(
"Function Name: {}",
function.function_name().unwrap_or_default()
);
}
let output = functions.len().to_string();
Ok(output)
}
#[derive(Debug, Clone)]
struct BrowserSleep;
impl AsyncSleep for BrowserSleep {
fn sleep(&self, duration: std::time::Duration) -> Sleep {
Sleep::new(Box::pin(async move {
wasm_timer::Delay::new(duration).await.unwrap();
}))
}
}
fn static_credential_provider() -> impl ProvideCredentials {
Credentials::from_keys(
"access_key",
"secret_key",
Some("session_token".to_string()),
)
}
fn browser_credentials_cache() -> CredentialsCache {
CredentialsCache::lazy_builder()
.sleep(std::sync::Arc::new(BrowserSleep))
.into_credentials_cache()
}
#[async_trait(?Send)]
trait MakeRequestBrowser {
async fn send(
parts: http::request::Parts,
body: SdkBody,
) -> Result<http::Response<SdkBody>, JsValue>;
}
pub struct BrowserHttpClient {}
#[async_trait(?Send)]
impl MakeRequestBrowser for BrowserHttpClient {
async fn send(
parts: http::request::Parts,
body: SdkBody,
) -> Result<http::Response<SdkBody>, JsValue> {
use js_sys::{Array, ArrayBuffer, Reflect, Uint8Array};
use wasm_bindgen_futures::JsFuture;
let mut opts = web_sys::RequestInit::new();
opts.method(parts.method.as_str());
opts.mode(web_sys::RequestMode::Cors);
let body_pinned = std::pin::Pin::new(body.bytes().unwrap());
if body_pinned.len() > 0 {
let uint_8_array = unsafe { Uint8Array::view(&body_pinned) };
opts.body(Some(&uint_8_array));
}
let request = web_sys::Request::new_with_str_and_init(&parts.uri.to_string(), &opts)?;
for (name, value) in parts
.headers
.iter()
.map(|(n, v)| (n.as_str(), v.to_str().unwrap()))
{
request.headers().set(name, value)?;
}
let window = web_sys::window().ok_or("could not get window")?;
let promise = window.fetch_with_request(&request);
let res_web = JsFuture::from(promise).await?;
let res_web: web_sys::Response = res_web.dyn_into().unwrap();
let promise_array = res_web.array_buffer()?;
let array = JsFuture::from(promise_array).await?;
let buf: ArrayBuffer = array.dyn_into().unwrap();
let slice = Uint8Array::new(&buf);
let body = slice.to_vec();
let mut builder = http::Response::builder().status(res_web.status());
for i in js_sys::try_iter(&res_web.headers())?.unwrap() {
let array: Array = i?.into();
let values = array.values();
let prop = String::from("value").into();
let key = Reflect::get(values.next()?.as_ref(), &prop)?
.as_string()
.unwrap();
let value = Reflect::get(values.next()?.as_ref(), &prop)?
.as_string()
.unwrap();
builder = builder.header(&key, &value);
}
let res_body = SdkBody::from(body);
let res = builder.body(res_body).unwrap();
Ok(res)
}
}
pub struct MockedHttpClient {}
#[async_trait(?Send)]
impl MakeRequestBrowser for MockedHttpClient {
async fn send(
_parts: http::request::Parts,
_body: SdkBody,
) -> Result<http::Response<SdkBody>, JsValue> {
let body = "{
\"Functions\": [
{
\"FunctionName\": \"function-name-1\"
},
{
\"FunctionName\": \"function-name-2\"
}
],
\"NextMarker\": null
}";
let builder = http::Response::builder().status(200);
let res = builder.body(SdkBody::from(body)).unwrap();
Ok(res)
}
}
#[derive(Debug, Clone)]
struct Adapter {
verbose: bool,
use_mock: bool,
}
impl Adapter {
fn new(verbose: bool, use_mock: bool) -> Self {
Self { verbose, use_mock }
}
}
impl tower::Service<http::Request<SdkBody>> for Adapter {
type Response = http::Response<SdkBody>;
type Error = ConnectorError;
#[allow(clippy::type_complexity)]
type Future = std::pin::Pin<
Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>,
>;
fn poll_ready(
&mut self,
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
std::task::Poll::Ready(Ok(()))
}
fn call(&mut self, req: http::Request<SdkBody>) -> Self::Future {
let (parts, body) = req.into_parts();
let uri = parts.uri.to_string();
if self.verbose {
log!("sending request to {}", uri);
log!("http::Request parts: {:?}", parts);
log!("http::Request body: {:?}", body);
log!("");
}
let (tx, rx) = tokio::sync::oneshot::channel();
log!("begin request...");
let use_mock = self.use_mock;
wasm_bindgen_futures::spawn_local(async move {
let fut = if use_mock {
MockedHttpClient::send(parts, body)
} else {
BrowserHttpClient::send(parts, body)
};
let _ = tx.send(
fut.await
.unwrap_or_else(|_| panic!("failure while making request to: {}", uri)),
);
});
Box::pin(async move {
let response = rx.await.map_err(|e| ConnectorError::user(Box::new(e)))?;
log!("response received");
Ok(response)
})
}
}