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
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
use crate::{
    cache::core::replace::ReplaceStrategy,
    handle::{BodyHandle, RequestHandle, StreamingBodyHandle},
};
use bytes::{Bytes, BytesMut};
use fastly_shared::{
    FastlyStatus, INVALID_CACHE_BUSY_HANDLE, INVALID_CACHE_HANDLE, INVALID_CACHE_REPLACE_HANDLE,
};
pub use fastly_sys::fastly_cache::{CacheDurationNs, CacheLookupState, CacheObjectLength};
use fastly_sys::{
    fastly_async_io::is_ready,
    fastly_cache::{self as sys, CacheHitCount},
};
use std::mem::ManuallyDrop;
use std::ptr;

/// A cache key consists of up to 4KiB of arbitrary bytes.
pub type CacheKey = Bytes;

#[derive(Debug, Default)]
pub struct LookupOptions<'a> {
    pub request_headers: Option<&'a RequestHandle>,
    pub service: Option<String>,
    pub always_use_requested_range: bool,
}

impl LookupOptions<'_> {
    fn as_abi(&self) -> (sys::CacheLookupOptionsMask, sys::CacheLookupOptions) {
        use sys::CacheLookupOptionsMask as Mask;

        let mut mask = Mask::empty();

        let request_headers = if let Some(v) = &self.request_headers {
            mask.insert(Mask::REQUEST_HEADERS);
            v.as_u32()
        } else {
            RequestHandle::INVALID.as_u32()
        };

        let (service, service_len) = if let Some(service) = self.service.as_deref() {
            mask.insert(Mask::SERVICE);
            (service.as_ptr(), service.len() as u32)
        } else {
            (std::ptr::null(), 0)
        };

        if self.always_use_requested_range {
            mask.insert(Mask::ALWAYS_USE_REQUESTED_RANGE)
        }

        let options = sys::CacheLookupOptions {
            request_headers,
            service,
            service_len,
        };
        (mask, options)
    }
}

#[derive(Debug, Default)]
pub struct ReplaceOptions<'a> {
    pub request_headers: Option<&'a RequestHandle>,
    pub replace_strategy: ReplaceStrategy,
    pub service: Option<String>,
    pub always_use_requested_range: bool,
}

impl ReplaceOptions<'_> {
    fn as_abi(&self) -> (sys::CacheReplaceOptionsMask, sys::CacheReplaceOptions) {
        use sys::CacheReplaceOptionsMask as Mask;

        let mut mask = Mask::empty();
        let request_headers = if let Some(v) = &self.request_headers {
            mask.insert(Mask::REQUEST_HEADERS);
            v.as_u32()
        } else {
            RequestHandle::INVALID.as_u32()
        };

        mask.insert(Mask::REPLACE_STRATEGY);
        let replace_strategy = match self.replace_strategy {
            ReplaceStrategy::Immediate => sys::CacheReplaceStrategy::Immediate,
            ReplaceStrategy::ImmediateForceMiss => sys::CacheReplaceStrategy::ImmediateForceMiss,
            ReplaceStrategy::Wait => sys::CacheReplaceStrategy::Wait,
        } as u32;

        let (service, service_len) = if let Some(service) = self.service.as_deref() {
            mask.insert(Mask::SERVICE);
            (service.as_ptr(), service.len() as u32)
        } else {
            (std::ptr::null(), 0)
        };
        if self.always_use_requested_range {
            mask.insert(Mask::ALWAYS_USE_REQUESTED_RANGE);
        }

        let options = sys::CacheReplaceOptions {
            request_headers,
            replace_strategy,
            service,
            service_len,
        };
        (mask, options)
    }
}

#[derive(Debug, Default)]
pub struct WriteOptions<'a> {
    pub max_age_ns: u64,
    pub request_headers: Option<&'a RequestHandle>,
    pub vary_rule: Option<&'a str>,
    pub initial_age_ns: Option<u64>,
    pub stale_while_revalidate_ns: Option<u64>,
    pub surrogate_keys: Option<&'a str>,
    pub length: Option<CacheObjectLength>,
    pub user_metadata: Option<Bytes>,
    pub sensitive_data: bool,
    pub edge_max_age_ns: Option<u64>,
    pub service: Option<String>,
}

impl WriteOptions<'_> {
    fn as_abi(&self) -> (sys::CacheWriteOptionsMask, sys::CacheWriteOptions) {
        use sys::CacheWriteOptionsMask as Mask;

        let mut mask = Mask::empty();
        let request_headers = if let Some(v) = &self.request_headers {
            mask.insert(Mask::REQUEST_HEADERS);
            v.as_u32()
        } else {
            RequestHandle::INVALID.as_u32()
        };
        let (vary_rule_ptr, vary_rule_len) = if let Some(v) = self.vary_rule {
            mask.insert(Mask::VARY_RULE);
            (v.as_ptr(), v.len())
        } else {
            (ptr::null(), 0)
        };
        let initial_age_ns = if let Some(v) = self.initial_age_ns {
            mask.insert(Mask::INITIAL_AGE_NS);
            v
        } else {
            0
        };
        let stale_while_revalidate_ns = if let Some(v) = self.stale_while_revalidate_ns {
            mask.insert(Mask::STALE_WHILE_REVALIDATE_NS);
            v
        } else {
            0
        };
        let (surrogate_keys_ptr, surrogate_keys_len) = if let Some(v) = self.surrogate_keys {
            mask.insert(Mask::SURROGATE_KEYS);
            (v.as_ptr(), v.len())
        } else {
            (ptr::null(), 0)
        };
        let length = if let Some(v) = self.length {
            mask.insert(Mask::LENGTH);
            v
        } else {
            0
        };
        let (user_metadata_ptr, user_metadata_len) = if let Some(v) = &self.user_metadata {
            mask.insert(Mask::USER_METADATA);
            (v.as_ptr(), v.len())
        } else {
            (ptr::null(), 0)
        };
        if self.sensitive_data {
            mask.insert(Mask::SENSITIVE_DATA);
        }
        let edge_max_age_ns = if let Some(v) = self.edge_max_age_ns {
            mask.insert(Mask::EDGE_MAX_AGE_NS);
            v
        } else {
            0
        };
        let (service, service_len) = if let Some(service) = self.service.as_deref() {
            mask.insert(Mask::SERVICE);
            (service.as_ptr(), service.len() as u32)
        } else {
            (std::ptr::null(), 0)
        };

        let options = sys::CacheWriteOptions {
            max_age_ns: self.max_age_ns,
            request_headers,
            vary_rule_ptr,
            vary_rule_len,
            initial_age_ns,
            stale_while_revalidate_ns,
            surrogate_keys_ptr,
            surrogate_keys_len,
            length,
            user_metadata_ptr,
            user_metadata_len,
            edge_max_age_ns,
            service,
            service_len,
        };
        (mask, options)
    }
}

#[derive(Debug, Default)]
pub struct GetBodyOptions {
    pub from: Option<u64>,
    pub to: Option<u64>,
}

impl GetBodyOptions {
    fn as_abi(&self) -> (sys::CacheGetBodyOptionsMask, sys::CacheGetBodyOptions) {
        use sys::CacheGetBodyOptionsMask as Mask;

        let mut mask = Mask::empty();
        let from = if let Some(v) = self.from {
            mask.insert(Mask::FROM);
            v
        } else {
            0
        };
        let to = if let Some(v) = self.to {
            mask.insert(Mask::TO);
            v
        } else {
            0
        };
        let options = sys::CacheGetBodyOptions { from, to };
        (mask, options)
    }
}

pub fn lookup(key: CacheKey, options: &LookupOptions) -> Result<CacheHandle, FastlyStatus> {
    let mut cache_handle_out = CacheHandle::INVALID;
    let (options_mask, options) = options.as_abi();
    unsafe {
        sys::lookup(
            key.as_ptr(),
            key.len(),
            options_mask,
            &options,
            cache_handle_out.as_abi_mut(),
        )
    }
    .result()?;
    Ok(cache_handle_out)
}

pub fn insert(key: CacheKey, options: &WriteOptions) -> Result<StreamingBodyHandle, FastlyStatus> {
    let mut body_handle_out = BodyHandle::INVALID;
    let (options_mask, options) = options.as_abi();
    unsafe {
        sys::insert(
            key.as_ptr(),
            key.len(),
            options_mask,
            &options,
            body_handle_out.as_u32_mut(),
        )
    }
    .result()?;
    Ok(StreamingBodyHandle::from_body_handle(body_handle_out))
}

pub fn replace(
    key: CacheKey,
    options: &ReplaceOptions,
) -> Result<CacheReplaceHandle, FastlyStatus> {
    let mut cache_handle_out = CacheReplaceHandle::INVALID;
    let (options_mask, options) = options.as_abi();
    unsafe {
        sys::replace(
            key.as_ptr(),
            key.len(),
            options_mask,
            &options,
            cache_handle_out.as_abi_mut(),
        )
    }
    .result()?;
    Ok(cache_handle_out)
}

pub fn transaction_lookup(
    key: CacheKey,
    options: &LookupOptions,
) -> Result<CacheHandle, FastlyStatus> {
    let mut cache_handle_out = CacheHandle::INVALID;
    let (options_mask, options) = options.as_abi();
    unsafe {
        sys::transaction_lookup(
            key.as_ptr(),
            key.len(),
            options_mask,
            &options,
            cache_handle_out.as_abi_mut(),
        )
    }
    .result()?;
    Ok(cache_handle_out)
}

pub fn transaction_lookup_async(
    key: CacheKey,
    options: &LookupOptions,
) -> Result<CacheBusyHandle, FastlyStatus> {
    let mut busy_handle_out = CacheBusyHandle::INVALID;
    let (options_mask, options) = options.as_abi();
    unsafe {
        sys::transaction_lookup_async(
            key.as_ptr(),
            key.len(),
            options_mask,
            &options,
            busy_handle_out.as_abi_mut(),
        )
    }
    .result()?;
    Ok(busy_handle_out)
}

/// Handle for an unresolved core cache operation.
pub struct CacheBusyHandle {
    busy_handle: sys::CacheBusyHandle,
}

impl CacheBusyHandle {
    #[cfg_attr(
        not(target_env = "p1"),
        deprecated(
            since = "0.11.6",
            note = "This code will need to be updated for wasip2."
        )
    )]
    const INVALID: Self = CacheBusyHandle {
        busy_handle: INVALID_CACHE_HANDLE,
    };

    fn is_invalid(&self) -> bool {
        self.busy_handle == INVALID_CACHE_BUSY_HANDLE
    }

    fn as_abi(&self) -> sys::CacheHandle {
        self.busy_handle
    }

    fn as_abi_mut(&mut self) -> &mut sys::CacheBusyHandle {
        &mut self.busy_handle
    }

    #[doc(hidden)]
    pub fn into_abi(self) -> sys::CacheBusyHandle {
        ManuallyDrop::new(self).busy_handle
    }

    #[doc(hidden)]
    pub fn from_abi(busy_handle: sys::CacheBusyHandle) -> Self {
        Self { busy_handle }
    }

    /// Returns `false` (that is, not read) if the request represented by this
    /// `BusyHandle` is not waiting behind another client, and `true` if it is.
    pub fn is_ready(&self) -> Result<bool, FastlyStatus> {
        let mut out = 0_u32;
        unsafe { is_ready(self.as_abi(), &mut out) }.result()?;

        match out {
            0 => Ok(false),
            _ => Ok(true),
        }
    }

    /// Wait for this request to resolve, including waiting for another client
    /// to provide the resulting item if necessary.
    pub fn wait(self) -> Result<CacheHandle, FastlyStatus> {
        let mut cache_handle_out = CacheHandle::INVALID;
        unsafe { sys::cache_busy_handle_wait(self.into_abi(), cache_handle_out.as_abi_mut()) }
            .result()?;
        Ok(cache_handle_out)
    }
}

impl Drop for CacheBusyHandle {
    fn drop(&mut self) {
        // Only try to close on drop if the handle is not invalid
        if !self.is_invalid() {
            unsafe {
                // TODO: This should expect a successful result, however for now
                // the result is ignored due to some occasional harmless errors.
                let _ = sys::close_busy(self.as_abi());
            }
        }
    }
}

pub struct CacheHandle {
    cache_handle: sys::CacheHandle,
}

impl Drop for CacheHandle {
    fn drop(&mut self) {
        // Only try to close on drop if the handle is not invalid
        if !self.is_invalid() {
            unsafe {
                // TODO: This should expect a successful result, however for now
                // the result is ignored due to some occasional harmless errors.
                let _ = sys::close(self.as_abi());
            }
        }
    }
}

impl CacheHandle {
    const INVALID: Self = CacheHandle {
        cache_handle: INVALID_CACHE_HANDLE,
    };

    fn is_invalid(&self) -> bool {
        self.cache_handle == INVALID_CACHE_HANDLE
    }

    fn as_abi(&self) -> sys::CacheHandle {
        self.cache_handle
    }

    fn as_abi_mut(&mut self) -> &mut sys::CacheHandle {
        &mut self.cache_handle
    }

    pub fn transaction_insert(
        &self,
        options: &WriteOptions,
    ) -> Result<StreamingBodyHandle, FastlyStatus> {
        let mut body_handle_out = BodyHandle::INVALID;
        let (options_mask, options) = options.as_abi();
        unsafe {
            sys::transaction_insert(
                self.as_abi(),
                options_mask,
                &options,
                body_handle_out.as_u32_mut(),
            )
        }
        .result()?;
        Ok(StreamingBodyHandle::from_body_handle(body_handle_out))
    }

    pub fn transaction_insert_and_stream_back(
        &self,
        options: &WriteOptions,
    ) -> Result<(StreamingBodyHandle, CacheHandle), FastlyStatus> {
        let mut body_handle_out = BodyHandle::INVALID;
        let mut cache_handle_out = CacheHandle::INVALID;
        let (options_mask, options) = options.as_abi();
        unsafe {
            sys::transaction_insert_and_stream_back(
                self.as_abi(),
                options_mask,
                &options,
                body_handle_out.as_u32_mut(),
                cache_handle_out.as_abi_mut(),
            )
        }
        .result()?;
        let streaming_body_handle = StreamingBodyHandle::from_body_handle(body_handle_out);
        Ok((streaming_body_handle, cache_handle_out))
    }

    pub fn transaction_update(&self, options: &WriteOptions) -> Result<(), FastlyStatus> {
        let (options_mask, options) = options.as_abi();
        unsafe { sys::transaction_update(self.as_abi(), options_mask, &options) }.result()
    }

    pub fn transaction_cancel(&self) -> Result<(), FastlyStatus> {
        unsafe { sys::transaction_cancel(self.as_abi()) }.result()
    }

    /// Transactions are internally asynchronous, but we don't yet fully expose that in the SDK.
    /// The internal asynchrony means that lookup errors can be deferred. Rather than making
    /// all accessors failable, we provide this method for forcing the underlying await and returning
    /// any error, after which accessors should be guaranteed to succeed without panicking.
    pub(crate) fn wait(&self) -> Result<(), FastlyStatus> {
        // use the `get_state` hostcall as an arbitrary choice of hostcall that will force the
        // await and surface any errors.
        let mut cache_lookup_state_out = CacheLookupState::empty();
        unsafe { sys::get_state(self.as_abi(), &mut cache_lookup_state_out) }.result()
    }

    pub fn get_state(&self) -> CacheLookupState {
        let mut cache_lookup_state_out = CacheLookupState::empty();
        unsafe { sys::get_state(self.as_abi(), &mut cache_lookup_state_out) }
            .result()
            .expect("sys::get_state failed");
        cache_lookup_state_out
    }

    pub fn get_user_metadata(&self) -> Option<Bytes> {
        const INITIAL_CAPACITY: usize = 16 * 1024;
        let mut user_metadata = BytesMut::with_capacity(INITIAL_CAPACITY);
        let mut nwritten_out = 0;
        let status = unsafe {
            sys::get_user_metadata(
                self.as_abi(),
                user_metadata.as_mut_ptr(),
                user_metadata.capacity(),
                &mut nwritten_out,
            )
        };
        match status {
            FastlyStatus::OK => {
                // Resize the byte string to the amount that was written out, and return it.
                unsafe { user_metadata.set_len(nwritten_out) };
                return Some(user_metadata.freeze());
            }
            FastlyStatus::NONE => {
                // No user metadata; handle is likely not in the `FOUND` state
                return None;
            }
            FastlyStatus::BUFLEN => {
                // The first attempt for user metadata may "fail" with a BUFLEN if the user metadata
                // is larger than `INITIAL_CAPACITY`, but the length we need will be written to
                // `nwritten_out`. This code path continues in the remainder of this function.
            }
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::get_user_metadata failed with {status:?}");
            }
        }
        // The length of `user_metadata` should be zero, and so it should be fine to just reserve
        // the amount returned in nwritten_out, but the subtraction guards against that assumption
        // changing.
        user_metadata.reserve(nwritten_out - user_metadata.len());
        unsafe {
            sys::get_user_metadata(
                self.as_abi(),
                user_metadata.as_mut_ptr(),
                user_metadata.capacity(),
                &mut nwritten_out,
            )
        }
        .result()
        .expect("sys::get_user_metadata failed");
        unsafe { user_metadata.set_len(nwritten_out) };
        Some(user_metadata.freeze())
    }

    pub fn get_body(&self, options: &GetBodyOptions) -> Result<Option<BodyHandle>, FastlyStatus> {
        let mut body_handle_out = BodyHandle::INVALID;
        let (options_mask, options) = options.as_abi();
        let status = unsafe {
            sys::get_body(
                self.as_abi(),
                options_mask,
                &options,
                body_handle_out.as_u32_mut(),
            )
        };
        match status {
            FastlyStatus::OK => Ok(Some(body_handle_out)),
            FastlyStatus::NONE => Ok(None),
            status => Err(status),
        }
    }

    pub fn get_length(&self) -> Option<CacheObjectLength> {
        let mut length_out = 0;
        let status = unsafe { sys::get_length(self.as_abi(), &mut length_out) };
        match status {
            FastlyStatus::OK => Some(length_out),
            FastlyStatus::NONE => None,
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::get_length failed with {status:?}");
            }
        }
    }

    pub fn get_max_age_ns(&self) -> Option<CacheDurationNs> {
        let mut duration_out = 0;
        let status = unsafe { sys::get_max_age_ns(self.as_abi(), &mut duration_out) };
        match status {
            FastlyStatus::OK => Some(duration_out),
            FastlyStatus::NONE => None,
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::get_max_age_ns failed with {status:?}");
            }
        }
    }

    pub fn get_stale_while_revalidate_ns(&self) -> Option<CacheDurationNs> {
        let mut duration_out = 0;
        let status =
            unsafe { sys::get_stale_while_revalidate_ns(self.as_abi(), &mut duration_out) };
        match status {
            FastlyStatus::OK => Some(duration_out),
            FastlyStatus::NONE => None,
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::get_stale_while_revalidate_ns failed with {status:?}");
            }
        }
    }

    pub fn get_age_ns(&self) -> Option<CacheDurationNs> {
        let mut duration_out = 0;
        let status = unsafe { sys::get_age_ns(self.as_abi(), &mut duration_out) };
        match status {
            FastlyStatus::OK => Some(duration_out),
            FastlyStatus::NONE => None,
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::get_age_ns failed with {status:?}");
            }
        }
    }

    pub fn get_hits(&self) -> Option<CacheHitCount> {
        let mut hits_out = 0;
        let status = unsafe { sys::get_hits(self.as_abi(), &mut hits_out) };
        match status {
            FastlyStatus::OK => Some(hits_out),
            FastlyStatus::NONE => None,
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::get_hits failed with {status:?}");
            }
        }
    }
}

pub struct CacheReplaceHandle {
    replace_handle: sys::CacheReplaceHandle,
}

impl Drop for CacheReplaceHandle {
    fn drop(&mut self) {
        // Only try to close on drop if the handle is not invalid
        if !self.is_invalid() {
            unsafe {
                // TODO: This should expect a successful result, however for now
                // the result is ignored due to some occasional harmless errors.
                let _ = sys::close(self.as_abi());
            }
        }
    }
}

impl CacheReplaceHandle {
    const INVALID: Self = CacheReplaceHandle {
        replace_handle: INVALID_CACHE_REPLACE_HANDLE,
    };

    fn is_invalid(&self) -> bool {
        self.replace_handle == INVALID_CACHE_REPLACE_HANDLE
    }

    fn as_abi(&self) -> sys::CacheHandle {
        self.replace_handle
    }

    fn as_abi_mut(&mut self) -> &mut sys::CacheHandle {
        &mut self.replace_handle
    }

    fn into_abi(self) -> sys::CacheHandle {
        ManuallyDrop::new(self).replace_handle
    }

    pub fn get_age_ns(&self) -> Option<CacheDurationNs> {
        let mut duration_out = 0;
        let status = unsafe { sys::replace_get_age_ns(self.as_abi(), &mut duration_out) };
        match status {
            FastlyStatus::OK => Some(duration_out),
            FastlyStatus::NONE => None,
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::replace_get_age_ns failed with {status:?}");
            }
        }
    }

    pub fn get_body(&self, options: &GetBodyOptions) -> Result<Option<BodyHandle>, FastlyStatus> {
        let mut body_handle_out = BodyHandle::INVALID;
        let (options_mask, options) = options.as_abi();
        let status = unsafe {
            sys::replace_get_body(
                self.as_abi(),
                options_mask,
                &options,
                body_handle_out.as_u32_mut(),
            )
        };
        match status {
            FastlyStatus::OK => Ok(Some(body_handle_out)),
            FastlyStatus::NONE => Ok(None),
            status => Err(status),
        }
    }

    pub fn get_hits(&self) -> Option<CacheHitCount> {
        let mut hits_out = 0;
        let status = unsafe { sys::replace_get_hits(self.as_abi(), &mut hits_out) };
        match status {
            FastlyStatus::OK => Some(hits_out),
            FastlyStatus::NONE => None,
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::replace_get_hits failed with {status:?}");
            }
        }
    }

    pub fn get_length(&self) -> Option<CacheObjectLength> {
        let mut length_out = 0;
        let status = unsafe { sys::replace_get_length(self.as_abi(), &mut length_out) };
        match status {
            FastlyStatus::OK => Some(length_out),
            FastlyStatus::NONE => None,
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::replace_get_length failed with {status:?}");
            }
        }
    }

    pub fn get_max_age_ns(&self) -> Option<CacheDurationNs> {
        let mut duration_out = 0;
        let status = unsafe { sys::replace_get_max_age_ns(self.as_abi(), &mut duration_out) };
        match status {
            FastlyStatus::OK => Some(duration_out),
            FastlyStatus::NONE => None,
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::replace_get_max_age_ns failed with {status:?}");
            }
        }
    }

    pub fn get_stale_while_revalidate_ns(&self) -> Option<CacheDurationNs> {
        let mut duration_out = 0;
        let status =
            unsafe { sys::replace_get_stale_while_revalidate_ns(self.as_abi(), &mut duration_out) };
        match status {
            FastlyStatus::OK => Some(duration_out),
            FastlyStatus::NONE => None,
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::replace_get_stale_while_revalidate_ns failed with {status:?}");
            }
        }
    }

    pub fn get_state(&self) -> CacheLookupState {
        let mut cache_lookup_state_out = CacheLookupState::empty();
        unsafe { sys::replace_get_state(self.as_abi(), &mut cache_lookup_state_out) }
            .result()
            .expect("sys::replace_get_state failed");
        cache_lookup_state_out
    }

    pub fn get_user_metadata(&self) -> Option<Bytes> {
        const INITIAL_CAPACITY: usize = 16 * 1024;
        let mut user_metadata = BytesMut::with_capacity(INITIAL_CAPACITY);
        let mut nwritten_out = 0;
        let status = unsafe {
            sys::replace_get_user_metadata(
                self.as_abi(),
                user_metadata.as_mut_ptr(),
                user_metadata.capacity(),
                &mut nwritten_out,
            )
        };
        match status {
            FastlyStatus::OK => {
                // Resize the byte string to the amount that was written out, and return it.
                unsafe { user_metadata.set_len(nwritten_out) };
                return Some(user_metadata.freeze());
            }
            FastlyStatus::NONE => {
                // No user metadata; handle is likely not in the `FOUND` state
                return None;
            }
            FastlyStatus::BUFLEN => {
                // The first attempt for user metadata may "fail" with a BUFLEN if the user metadata
                // is larger than `INITIAL_CAPACITY`, but the length we need will be written to
                // `nwritten_out`. This code path continues in the remainder of this function.
            }
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::replace_get_user_metadata failed with {status:?}");
            }
        }
        // The length of `user_metadata` should be zero, and so it should be fine to just reserve
        // the amount returned in nwritten_out, but the subtraction guards against that assumption
        // changing.
        user_metadata.reserve(nwritten_out - user_metadata.len());
        unsafe {
            sys::replace_get_user_metadata(
                self.as_abi(),
                user_metadata.as_mut_ptr(),
                user_metadata.capacity(),
                &mut nwritten_out,
            )
        }
        .result()
        .expect("sys::replace_get_user_metadata failed");
        unsafe { user_metadata.set_len(nwritten_out) };
        Some(user_metadata.freeze())
    }

    pub fn replace_insert(
        self,
        options: &WriteOptions,
    ) -> Result<StreamingBodyHandle, FastlyStatus> {
        let mut body_handle_out = BodyHandle::INVALID;

        let (options_mask, options) = options.as_abi();

        unsafe {
            sys::replace_insert(
                self.into_abi(),
                options_mask,
                &options,
                body_handle_out.as_u32_mut(),
            )
        }
        .result()?;

        Ok(StreamingBodyHandle::from_body_handle(body_handle_out))
    }
}