fastly 0.12.0

Fastly Compute API
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
//! Safe abstractions around the KV Store FFI.
use crate::handle::BodyHandle;
use crate::kv_store::{ListResponse, LookupResponse};
use bytes::BytesMut;
use fastly_shared::{
    FastlyStatus, INVALID_BODY_HANDLE, INVALID_KV_PENDING_DELETE_HANDLE,
    INVALID_KV_PENDING_INSERT_HANDLE, INVALID_KV_PENDING_LIST_HANDLE,
    INVALID_KV_PENDING_LOOKUP_HANDLE, INVALID_KV_STORE_HANDLE,
};
use fastly_sys::fastly_kv_store as sys;
use fastly_sys::ListModeInternal;
pub use fastly_sys::{
    DeleteConfig, DeleteConfigOptions, InsertConfig, InsertConfigOptions, InsertMode, ListConfig,
    ListConfigOptions, ListMode, LookupConfig, LookupConfigOptions,
};
use serde_json;
use sys::KvError as KvSysError;

pub const METADATA_MAX_BYTES: usize = 2000;

/// Errors that can arise during KV Store operations.
///
/// This type is marked as non-exhaustive because more variants will be added over time.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum KVStoreError {
    /// The key provided for this operation was not valid.
    #[error("Invalid KV Store key")]
    InvalidKey,
    /// The KV Store handle provided for this operation was not valid.
    #[error("Invalid KV Store handle")]
    InvalidStoreHandle,
    /// The options provided for this operation were not valid.
    #[error("Invalid KV Store options")]
    InvalidStoreOptions,
    /// KV Store item request was bad.
    #[error("KV Store item request was bad")]
    ItemBadRequest,
    /// No KV Store item by this name exists.
    #[error("KV Store item not found")]
    ItemNotFound,
    /// KV Store item precondition failed.
    #[error("KV Store item precondition failed")]
    ItemPreconditionFailed,
    /// No KV Store item exceeded payload limit.
    #[error("KV Store item exceeded payload limit")]
    ItemPayloadTooLarge,
    /// No KV Store by this name exists.
    #[error("KV Store {0:?} not found")]
    StoreNotFound(String),
    /// Too many requests have been sent, hitting a rate limit.
    #[error("Too many KV Store requests")]
    TooManyRequests,
    /// Some unexpected error occurred.
    #[error("Unexpected KV Store error: {0:?}")]
    Unexpected(FastlyStatus),
}

impl From<FastlyStatus> for KVStoreError {
    fn from(st: FastlyStatus) -> Self {
        KVStoreError::Unexpected(st)
    }
}

impl From<KvSysError> for KVStoreError {
    fn from(err: KvSysError) -> Self {
        match err {
            // this should never be `Uninitialized`,
            // `Uninitialized` needs to be caught before into()
            KvSysError::Uninitialized => KVStoreError::Unexpected(FastlyStatus::ERROR),
            // this should never be `Ok`,
            // if it's `Ok`, we shouldn't be using into()
            KvSysError::Ok => KVStoreError::Unexpected(FastlyStatus::ERROR),
            KvSysError::BadRequest => KVStoreError::ItemBadRequest,
            KvSysError::NotFound => KVStoreError::ItemNotFound,
            KvSysError::PreconditionFailed => KVStoreError::ItemPreconditionFailed,
            KvSysError::PayloadTooLarge => KVStoreError::ItemPayloadTooLarge,
            KvSysError::InternalError => KVStoreError::Unexpected(FastlyStatus::ERROR),
        }
    }
}

/// A handle to a pending asynchronous lookup returned by
/// [`LookupBuilder::execute_async()`][`crate::LookupBuilder::execute_async()`].
///
/// A handle can be evaluated using [`KVStore::pending_lookup_wait()`][`crate::KVStore::pending_lookup_wait()`].
pub struct PendingLookupHandle {
    pub(super) handle: u32,
}

impl PendingLookupHandle {
    /// Get the underlying representation of the handle.
    ///
    /// This should only be used when calling the raw ABI directly, and care should be taken not to
    /// reuse or alias handle values.
    #[cfg_attr(
        not(target_env = "p1"),
        deprecated(
            since = "0.11.6",
            note = "This code will need to be updated for wasip2."
        )
    )]
    pub fn as_u32(&self) -> u32 {
        self.handle
    }

    /// Make a handle from its underlying representation.
    ///
    /// This should only be used when calling the raw ABI directly, and care should be taken not to
    /// reuse or alias handle values.
    #[cfg_attr(
        not(target_env = "p1"),
        deprecated(
            since = "0.11.6",
            note = "This code will need to be updated for wasip2."
        )
    )]
    pub unsafe fn from_u32(handle: u32) -> Self {
        Self { handle }
    }
}

/// A handle to a pending asynchronous insert returned by
/// [`InsertBuilder::execute_async()`][`crate::InsertBuilder::execute_async()`].
///
/// A handle can be evaluated using [`KVStore::pending_insert_wait()`][`crate::KVStore::pending_insert_wait()`]. It
/// can also be discarded if the request was sent for effects it might have, and the response is
/// unimportant.
pub struct PendingInsertHandle {
    pub(super) handle: u32,
}

impl PendingInsertHandle {
    /// Get the underlying representation of the handle.
    ///
    /// This should only be used when calling the raw ABI directly, and care should be taken not to
    /// reuse or alias handle values.
    #[cfg_attr(
        not(target_env = "p1"),
        deprecated(
            since = "0.11.6",
            note = "This code will need to be updated for wasip2."
        )
    )]
    pub fn as_u32(&self) -> u32 {
        self.handle
    }

    /// Make a handle from its underlying representation.
    ///
    /// This should only be used when calling the raw ABI directly, and care should be taken not to
    /// reuse or alias handle values.
    #[cfg_attr(
        not(target_env = "p1"),
        deprecated(
            since = "0.11.6",
            note = "This code will need to be updated for wasip2."
        )
    )]
    pub unsafe fn from_u32(handle: u32) -> Self {
        Self { handle }
    }
}

/// A handle to a pending asynchronous delete returned by
/// [`DeleteBuilder::execute_async()`][`crate::DeleteBuilder::execute_async()`].
///
/// A handle can be evaluated using [`KVStore::pending_delete_wait()`][`crate::KVStore::pending_delete_wait()`]. It
/// can also be discarded if the request was sent for effects it might have, and the response is
/// unimportant.
pub struct PendingDeleteHandle {
    pub(super) handle: u32,
}

impl PendingDeleteHandle {
    /// Get the underlying representation of the handle.
    ///
    /// This should only be used when calling the raw ABI directly, and care should be taken not to
    /// reuse or alias handle values.
    #[cfg_attr(
        not(target_env = "p1"),
        deprecated(
            since = "0.11.6",
            note = "This code will need to be updated for wasip2."
        )
    )]
    pub fn as_u32(&self) -> u32 {
        self.handle
    }

    /// Make a handle from its underlying representation.
    ///
    /// This should only be used when calling the raw ABI directly, and care should be taken not to
    /// reuse or alias handle values.
    #[cfg_attr(
        not(target_env = "p1"),
        deprecated(
            since = "0.11.6",
            note = "This code will need to be updated for wasip2."
        )
    )]
    pub unsafe fn from_u32(handle: u32) -> Self {
        Self { handle }
    }
}

/// A handle to a pending asynchronous list returned by
/// [`ListBuilder::execute_async()`][`crate::ListBuilder::execute_async()`].
///
/// A handle can be evaluated using [`KVStore::pending_list_wait()`][`crate::KVStore::pending_list_wait()`].
pub struct PendingListHandle {
    pub(super) handle: u32,
}

impl PendingListHandle {
    /// Get the underlying representation of the handle.
    ///
    /// This should only be used when calling the raw ABI directly, and care should be taken not to
    /// reuse or alias handle values.
    #[cfg_attr(
        not(target_env = "p1"),
        deprecated(
            since = "0.11.6",
            note = "This code will need to be updated for wasip2."
        )
    )]
    pub fn as_u32(&self) -> u32 {
        self.handle
    }

    /// Make a handle from its underlying representation.
    ///
    /// This should only be used when calling the raw ABI directly, and care should be taken not to
    /// reuse or alias handle values.
    #[cfg_attr(
        not(target_env = "p1"),
        deprecated(
            since = "0.11.6",
            note = "This code will need to be updated for wasip2."
        )
    )]
    pub unsafe fn from_u32(handle: u32) -> Self {
        Self { handle }
    }
}

/// A handle to a key-value store that is open for lookups and inserting.
#[derive(Debug, Eq, Hash, PartialEq)]
#[repr(transparent)]
pub struct StoreHandle {
    handle: u32,
}

impl StoreHandle {
    /// Get the underlying representation of the handle.
    ///
    /// This should only be used when calling the raw ABI directly, and care should be taken not to
    /// reuse or alias handle values.
    #[cfg_attr(
        not(target_env = "p1"),
        deprecated(
            since = "0.11.6",
            note = "This code will need to be updated for wasip2."
        )
    )]
    pub fn as_u32(&self) -> u32 {
        self.handle
    }

    /// Open a handle to the KV Store with the given name.
    pub fn open(name: &str) -> Result<Option<StoreHandle>, KVStoreError> {
        let mut store_handle_out = INVALID_KV_STORE_HANDLE;
        let status = unsafe { sys::open_v2(name.as_ptr(), name.len(), &mut store_handle_out) };
        status.result().map_err(|st| match st {
            FastlyStatus::INVAL => KVStoreError::StoreNotFound(name.to_owned()),
            _ => st.into(),
        })?;
        if store_handle_out == INVALID_KV_STORE_HANDLE {
            Ok(None)
        } else {
            Ok(Some(StoreHandle {
                handle: store_handle_out,
            }))
        }
    }

    /// Look up a value in the KV Store.
    ///
    /// Returns `Ok(PendingLookupHandle)` if the creation of the async request was successful.
    pub fn lookup(&self, key: impl AsRef<[u8]>) -> Result<PendingLookupHandle, KVStoreError> {
        let mut pending_lookup_handle_out = INVALID_KV_PENDING_LOOKUP_HANDLE;
        let key = key.as_ref();
        let config_options = LookupConfigOptions::empty();
        let config = LookupConfig::default();
        let status = unsafe {
            sys::lookup_v2(
                self.as_u32(),
                key.as_ptr(),
                key.len(),
                config_options,
                &config,
                &mut pending_lookup_handle_out,
            )
        };
        status.result().map_err(|st| match st {
            FastlyStatus::BADF => KVStoreError::InvalidStoreHandle,
            FastlyStatus::INVAL => KVStoreError::ItemBadRequest,
            _ => st.into(),
        })?;
        if pending_lookup_handle_out == INVALID_KV_PENDING_LOOKUP_HANDLE {
            Err(KVStoreError::Unexpected(FastlyStatus::ERROR))
        } else {
            Ok(unsafe { PendingLookupHandle::from_u32(pending_lookup_handle_out) })
        }
    }

    /// Wait on the async lookup of a value in the KV Store.
    ///
    /// Returns `Ok(LookupResponse)` if a value is found, and `Err(KVStoreError)` if an error has occured.
    pub fn pending_lookup_wait(
        &self,
        pending_lookup_handle: PendingLookupHandle,
    ) -> Result<LookupResponse, KVStoreError> {
        let mut body_handle_out = INVALID_BODY_HANDLE;
        let metadata_buf_len = METADATA_MAX_BYTES;
        let mut metadata_buf = BytesMut::zeroed(metadata_buf_len);
        let mut metadata_len_out = 0usize;
        let mut generation = 0u64;
        let mut kv_sys_error = KvSysError::Uninitialized;

        let status = unsafe {
            sys::lookup_wait_v2(
                pending_lookup_handle.as_u32(),
                &mut body_handle_out,
                metadata_buf.as_mut_ptr(),
                metadata_buf_len,
                &mut metadata_len_out,
                &mut generation,
                &mut kv_sys_error,
            )
        };

        status.result().map_err(|st| match st {
            FastlyStatus::BADF => KVStoreError::InvalidStoreHandle,
            FastlyStatus::INVAL => KVStoreError::ItemBadRequest,
            _ => st.into(),
        })?;

        let metadata = match metadata_len_out {
            0 => None,
            _ => {
                unsafe {
                    metadata_buf.set_len(metadata_len_out);
                }
                Some(metadata_buf.freeze())
            }
        };

        if kv_sys_error != KvSysError::Ok {
            return Err(kv_sys_error.into());
        }

        if body_handle_out == INVALID_BODY_HANDLE {
            Err(KVStoreError::Unexpected(FastlyStatus::ERROR))
        } else {
            Ok(LookupResponse {
                body: unsafe { Some(BodyHandle::from_u32(body_handle_out).into()) },
                metadata,
                generation,
            })
        }
    }

    /// Insert a value into the KV Store.
    ///
    /// If the KV Store already contains a value for this key, it will be overwritten.
    pub fn insert(
        &self,
        key: impl AsRef<str>,
        value: BodyHandle,
        mode: InsertMode,
        background_fetch: bool,
        if_generation_match: Option<u64>,
        metadata: impl AsRef<str>,
        time_to_live_sec: Option<std::time::Duration>,
    ) -> Result<PendingInsertHandle, KVStoreError> {
        let key = key.as_ref();
        let metadata = metadata.as_ref();

        let mut config_options = InsertConfigOptions::empty();
        let mut config = InsertConfig::default();

        config.mode = mode;

        if background_fetch {
            config_options.insert(InsertConfigOptions::BACKGROUND_FETCH);
        }

        if let Some(igm) = if_generation_match {
            config.if_generation_match = igm;
            config_options.insert(InsertConfigOptions::IF_GENERATION_MATCH);
        }

        if !metadata.is_empty() {
            config.metadata = metadata.as_ptr();
            config.metadata_len = metadata.len() as u32;
            config_options.insert(InsertConfigOptions::METADATA);
        }

        if let Some(ttl) = time_to_live_sec {
            config.time_to_live_sec = ttl.as_secs().try_into().unwrap_or_default();
            config_options.insert(InsertConfigOptions::TIME_TO_LIVE_SEC);
        }

        let mut pending_insert_handle_out = INVALID_KV_PENDING_INSERT_HANDLE;

        let status = unsafe {
            sys::insert_v2(
                self.as_u32(),
                key.as_ptr(),
                key.len(),
                value.into_u32(),
                config_options,
                &config,
                &mut pending_insert_handle_out,
            )
        };
        status.result().map_err(|st| match st {
            FastlyStatus::BADF => KVStoreError::InvalidStoreHandle,
            FastlyStatus::INVAL => KVStoreError::ItemBadRequest,
            _ => st.into(),
        })?;
        if pending_insert_handle_out == INVALID_KV_PENDING_INSERT_HANDLE {
            Err(KVStoreError::Unexpected(FastlyStatus::ERROR))
        } else {
            Ok(unsafe { PendingInsertHandle::from_u32(pending_insert_handle_out) })
        }
    }

    /// Wait on the async insert of a value in the KV Store.
    ///
    /// Returns `Ok(())` if insert is a success, and `KVStoreError` on failure
    pub fn pending_insert_wait(
        &self,
        pending_insert_handle: PendingInsertHandle,
    ) -> Result<(), KVStoreError> {
        let mut kv_sys_error = KvSysError::Uninitialized;
        let status = unsafe {
            sys::pending_insert_wait_v2(pending_insert_handle.as_u32(), &mut kv_sys_error)
        };
        status.result().map_err(|st| match st {
            FastlyStatus::BADF => KVStoreError::InvalidStoreHandle,
            FastlyStatus::INVAL => KVStoreError::ItemBadRequest,
            FastlyStatus::LIMITEXCEEDED => KVStoreError::TooManyRequests,
            _ => st.into(),
        })?;

        if kv_sys_error != KvSysError::Ok {
            return Err(kv_sys_error.into());
        }

        Ok(())
    }

    /// Create async delete of a value in the KV Store.
    ///
    /// Returns `Ok(PendingDeleteHandle)` if the creation of the async request was successful.
    pub fn delete(&self, key: impl AsRef<str>) -> Result<PendingDeleteHandle, KVStoreError> {
        let mut pending_delete_handle_out = INVALID_KV_PENDING_DELETE_HANDLE;
        let key = key.as_ref();
        let status = unsafe {
            sys::delete_v2(
                self.as_u32(),
                key.as_ptr(),
                key.len(),
                DeleteConfigOptions::empty(),
                &DeleteConfig::default(),
                &mut pending_delete_handle_out,
            )
        };
        status.result().map_err(|st| match st {
            FastlyStatus::BADF => KVStoreError::InvalidStoreHandle,
            FastlyStatus::INVAL => KVStoreError::ItemBadRequest,
            _ => st.into(),
        })?;
        Ok(unsafe { PendingDeleteHandle::from_u32(pending_delete_handle_out) })
    }

    /// Wait on the async delete of a value in the KV Store.
    ///
    /// Returns `Ok(())` if delete is a success, and `KVStoreError` on failure
    pub fn pending_delete_wait(
        &self,
        pending_delete_handle: PendingDeleteHandle,
    ) -> Result<(), KVStoreError> {
        let mut kv_sys_error = KvSysError::Uninitialized;
        let status = unsafe {
            sys::pending_delete_wait_v2(pending_delete_handle.as_u32(), &mut kv_sys_error)
        };
        status.result().map_err(|st| match st {
            FastlyStatus::BADF => KVStoreError::InvalidStoreHandle,
            FastlyStatus::INVAL => KVStoreError::ItemBadRequest,
            _ => st.into(),
        })?;

        if kv_sys_error != KvSysError::Ok {
            return Err(kv_sys_error.into());
        }
        Ok(())
    }

    /// Create async list of keys in the KV Store.
    ///
    /// Returns `Ok(PendingListHandle)` if the creation of the async request was successful.
    pub fn list(
        &self,
        mode: ListMode,
        cursor: Option<String>,
        limit: Option<u32>,
        prefix: Option<String>,
    ) -> Result<PendingListHandle, KVStoreError> {
        let mut pending_list_handle_out = INVALID_KV_PENDING_LIST_HANDLE;

        let prefix = prefix.as_ref();

        let mut config_options = ListConfigOptions::empty();
        let mut config = ListConfig::default();

        config.mode = match mode {
            ListMode::Strong | ListMode::Other(_) => ListModeInternal::Strong,
            ListMode::Eventual => ListModeInternal::Eventual,
        };

        if let Some(c) = &cursor {
            if !c.is_empty() {
                config.cursor = c.as_ptr();
                config.cursor_len = c.len() as u32;
                config_options.insert(ListConfigOptions::CURSOR);
            }
        }

        if let Some(l) = limit {
            config.limit = l;
            config_options.insert(ListConfigOptions::LIMIT);
        }

        if let Some(p) = prefix {
            if !p.is_empty() {
                config.prefix = p.as_ptr();
                config.prefix_len = p.len() as u32;
                config_options.insert(ListConfigOptions::PREFIX);
            }
        }

        let status = unsafe {
            sys::list_v2(
                self.as_u32(),
                config_options,
                &config,
                &mut pending_list_handle_out,
            )
        };
        status.result().map_err(|st| match st {
            FastlyStatus::BADF => KVStoreError::InvalidStoreHandle,
            _ => st.into(),
        })?;
        Ok(unsafe { PendingListHandle::from_u32(pending_list_handle_out) })
    }

    /// Wait on the async list of keys in the KV Store.
    ///
    /// Returns `Ok(ListResponse)` if the request was successful
    pub fn pending_list_wait(
        &self,
        pending_list_handle: PendingListHandle,
    ) -> Result<ListResponse<'_>, KVStoreError> {
        let mut kv_sys_error = KvSysError::Uninitialized;
        let mut body_handle_out = INVALID_BODY_HANDLE;
        let status = unsafe {
            sys::pending_list_wait_v2(
                pending_list_handle.as_u32(),
                &mut body_handle_out,
                &mut kv_sys_error,
            )
        };

        status.result().map_err(|st| match st {
            FastlyStatus::BADF => KVStoreError::InvalidStoreHandle,
            _ => st.into(),
        })?;

        if kv_sys_error != KvSysError::Ok {
            return Err(kv_sys_error.into());
        }

        if body_handle_out == INVALID_BODY_HANDLE {
            Err(KVStoreError::Unexpected(FastlyStatus::ERROR))
        } else {
            let body = unsafe { BodyHandle::from_u32(body_handle_out) };
            let lrp = serde_json::from_reader(body)
                .map_err(|_| KVStoreError::Unexpected(FastlyStatus::ERROR))?;

            Ok(ListResponse {
                store_handle: self,
                page: lrp,
                iterator_did_error: false,
            })
        }
    }
}