-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.rs
324 lines (291 loc) · 10.3 KB
/
builder.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
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
use js_sys::{ArrayBuffer, Function, Object, Promise, Uint8Array};
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture;
use std::future::Future;
use std::pin::Pin;
use crate::{KvError, ListResponse};
struct InnerFuture {
fut: Pin<Box<dyn Future<Output = Result<JsValue, JsValue>> + 'static>>,
}
impl InnerFuture {
fn new<F: Future<Output = Result<JsValue, JsValue>> + 'static>(fut: F) -> Pin<Box<Self>> {
Box::pin(Self { fut: Box::pin(fut) })
}
}
impl Future for InnerFuture {
type Output = Result<JsValue, JsValue>;
fn poll(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
unsafe { Pin::new_unchecked(&mut self.fut).poll(cx) }
}
}
unsafe impl Send for InnerFuture {}
unsafe impl Sync for InnerFuture {}
struct InnerFuture2 {
fut: Pin<Box<dyn Future<Output = Result<JsValue, KvError>> + 'static>>,
}
impl InnerFuture2 {
fn new<F: Future<Output = Result<JsValue, KvError>> + 'static>(fut: F) -> Pin<Box<Self>> {
Box::pin(Self { fut: Box::pin(fut) })
}
}
impl Future for InnerFuture2 {
type Output = Result<JsValue, KvError>;
fn poll(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Self::Output> {
unsafe { Pin::new_unchecked(&mut self.fut).poll(cx) }
}
}
unsafe impl Send for InnerFuture2 {}
unsafe impl Sync for InnerFuture2 {}
/// A builder to configure put requests.
#[derive(Debug, Clone, Serialize)]
pub struct PutOptionsBuilder {
#[serde(skip)]
pub(crate) this: Object,
#[serde(skip)]
pub(crate) put_function: Function,
#[serde(skip)]
pub(crate) name: JsValue,
#[serde(skip)]
pub(crate) value: JsValue,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) expiration: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(rename = "expirationTtl")]
pub(crate) expiration_ttl: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) metadata: Option<Value>,
}
impl PutOptionsBuilder {
/// When (expressed as a [unix timestamp](https://en.wikipedia.org/wiki/Unix_time)) the key
/// value pair will expire in the store.
pub fn expiration(mut self, expiration: u64) -> Self {
self.expiration = Some(expiration);
self
}
/// How many seconds until the key value pair will expire.
pub fn expiration_ttl(mut self, expiration_ttl: u64) -> Self {
self.expiration_ttl = Some(expiration_ttl);
self
}
/// Metadata to be stored with the key value pair.
pub fn metadata<T: Serialize>(mut self, metadata: T) -> Result<Self, KvError> {
self.metadata = Some(serde_json::to_value(metadata)?);
Ok(self)
}
/// Puts the value in the kv store.
pub async fn execute(self) -> Result<(), KvError> {
let options_object = JsValue::from_serde(&self)?;
let promise: Promise = self
.put_function
.call3(&self.this, &self.name, &self.value, &options_object)?
.into();
JsFuture::from(promise)
.await
.map(|_| ())
.map_err(KvError::from)
}
}
/// A builder to configure list requests.
#[derive(Debug, Clone, Serialize)]
pub struct ListOptionsBuilder {
#[serde(skip)]
pub(crate) this: Object,
#[serde(skip)]
pub(crate) list_function: Function,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) limit: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) cursor: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) prefix: Option<String>,
}
impl ListOptionsBuilder {
/// The maximum number of keys returned. The default is 1000, which is the maximum. It is
/// unlikely that you will want to change this default, but it is included for completeness.
pub fn limit(mut self, limit: u64) -> Self {
self.limit = Some(limit);
self
}
/// A string returned by a previous response used to paginate the keys in the store.
pub fn cursor(mut self, cursor: String) -> Self {
self.cursor = Some(cursor);
self
}
/// A prefix that all keys must start with for them to be included in the response.
pub fn prefix(mut self, prefix: String) -> Self {
self.prefix = Some(prefix);
self
}
/// Lists the key value pairs in the kv store.
pub async fn execute(self) -> Result<ListResponse, KvError> {
let options_object = JsValue::from_serde(&self)?;
let promise: Promise = self
.list_function
.call1(&self.this, &options_object)?
.into();
JsFuture::from(promise)
.await?
.into_serde()
.map_err(KvError::from)
}
}
/// A builder to configure get requests.
#[derive(Debug, Clone, Serialize)]
pub struct GetOptionsBuilder {
#[serde(skip)]
pub(crate) this: Object,
#[serde(skip)]
pub(crate) get_function: Function,
#[serde(skip)]
pub(crate) get_with_meta_function: Function,
#[serde(skip)]
pub(crate) name: JsValue,
#[serde(rename = "cacheTtl", skip_serializing_if = "Option::is_none")]
pub(crate) cache_ttl: Option<u64>,
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub(crate) value_type: Option<GetValueType>,
}
impl GetOptionsBuilder {
/// The cache_ttl parameter must be an integer that is greater than or equal to 60. It defines
/// the length of time in seconds that a KV result is cached in the edge location that it is
/// accessed from. This can be useful for reducing cold read latency on keys that are read
/// relatively infrequently. It is especially useful if your data is write-once or
/// write-rarely, but is not recommended if your data is updated often and you need to see
/// updates shortly after they're written, because writes that happen from other edge locations
/// won't be visible until the cached value expires.
pub fn cache_ttl(mut self, cache_ttl: u64) -> Self {
self.cache_ttl = Some(cache_ttl);
self
}
fn value_type(mut self, value_type: GetValueType) -> Self {
self.value_type = Some(value_type);
self
}
async fn get(self) -> Result<JsValue, KvError> {
let options_object = JsValue::from_serde(&self)?;
let promise: Promise = self
.get_function
.call2(&self.this, &self.name, &options_object)?
.into();
let box_future = InnerFuture::new(JsFuture::from(promise));
unsafe {
Ok(Pin::new_unchecked(box_future).await.map_err(KvError::from)?)
}
// Ok(JsFuture::from(promise).await.map_err(KvError::from)?)
}
/// Gets the value as a string.
pub async fn text(self) -> Result<Option<String>, KvError> {
//let value = self.value_type(GetValueType::Text).get().await?;
let box_future = InnerFuture2::new(self.value_type(GetValueType::Text).get());
unsafe {
let value = Pin::new_unchecked(box_future).await?.as_string();
Ok(value)
}
}
/// Tries to deserialize the inner text to the generic type.
pub async fn json<T>(self) -> Result<Option<T>, KvError>
where
T: DeserializeOwned,
{
let value = self.value_type(GetValueType::Json).get().await?;
Ok(if value.is_null() {
None
} else {
Some(value.into_serde().map_err(KvError::from)?)
})
}
/// Gets the value as a byte slice.
pub async fn bytes(self) -> Result<Option<Vec<u8>>, KvError> {
let v = self.value_type(GetValueType::ArrayBuffer).get().await?;
if ArrayBuffer::instanceof(&v) {
let buffer = ArrayBuffer::from(v);
let buffer = Uint8Array::new(&buffer);
Ok(Some(buffer.to_vec()))
} else {
Ok(None)
}
}
async fn get_with_metadata<M>(&self) -> Result<(JsValue, Option<M>), KvError>
where
M: DeserializeOwned,
{
let options_object = JsValue::from_serde(&self)?;
let promise: Promise = self
.get_with_meta_function
.call2(&self.this, &self.name, &options_object)?
.into();
let pair = JsFuture::from(promise).await?;
let metadata = crate::get(&pair, "metadata")?;
let value = crate::get(&pair, "value")?;
Ok((
value,
if metadata.is_null() {
None
} else {
Some(metadata.into_serde().map_err(KvError::from)?)
},
))
}
/// Gets the value as a string and it's associated metadata.
pub async fn text_with_metadata<M>(self) -> Result<(Option<String>, Option<M>), KvError>
where
M: DeserializeOwned,
{
let (value, metadata) = self
.value_type(GetValueType::Text)
.get_with_metadata()
.await?;
Ok((value.as_string(), metadata))
}
/// Tries to deserialize the inner text to the generic type along with it's metadata.
pub async fn json_with_metadata<T, M>(self) -> Result<(Option<T>, Option<M>), KvError>
where
T: DeserializeOwned,
M: DeserializeOwned,
{
let (value, metadata) = self
.value_type(GetValueType::Json)
.get_with_metadata()
.await?;
Ok((
if value.is_null() {
None
} else {
Some(value.into_serde().map_err(KvError::from)?)
},
metadata,
))
}
/// Gets the value as a byte slice and it's associated metadata.
pub async fn bytes_with_metadata<M>(self) -> Result<(Option<Vec<u8>>, Option<M>), KvError>
where
M: DeserializeOwned,
{
let (value, metadata) = self
.value_type(GetValueType::ArrayBuffer)
.get_with_metadata()
.await?;
if ArrayBuffer::instanceof(&value) {
let buffer = ArrayBuffer::from(value);
let buffer = Uint8Array::new(&buffer);
Ok((Some(buffer.to_vec()), metadata))
} else {
Ok((None, metadata))
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) enum GetValueType {
Text,
ArrayBuffer,
Json,
}