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
//! Basic ABI wrappers for `fastly_http_cache` hostcalls.

use crate::{
    handle::{BodyHandle, RequestHandle, ResponseHandle, StreamingBodyHandle},
    Response,
};
use bytes::Bytes;
use fastly_shared::FastlyStatus;
use fastly_sys::{
    fastly_cache::{CacheDurationNs, CacheHitCount, CacheLookupState, CacheObjectLength},
    fastly_http_cache as sys,
};
use std::{ptr, time::Duration};

// Used for vary and surrogate keys
const INITIAL_BUF_SIZE: usize = 4096;

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

pub use sys::HttpStorageAction;

/// Errors arising from HTTP cache operations.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum HttpCacheError {
    /// Operation failed due to a limit.
    #[error("cache operation failed due to a limit")]
    LimitExceeded,
    /// Operation was not valid to be performed given the state of the cached item.
    #[error("invalid cache operation")]
    InvalidOperation,
    /// Cache operation is not supported.
    #[error("unsupported cache operation")]
    Unsupported,
    /// Cache operation indicated, on miss, an invalid backend would be used
    #[error("invalid backend")]
    InvalidBackend,
    /// An unknown error occurred.
    #[error("unknown cache operation error; please report this as a bug: {0:?}")]
    Other(FastlyStatus),
}

impl From<FastlyStatus> for HttpCacheError {
    fn from(status: FastlyStatus) -> Self {
        match status {
            FastlyStatus::UNSUPPORTED => HttpCacheError::Unsupported,
            FastlyStatus::LIMITEXCEEDED => HttpCacheError::LimitExceeded,
            FastlyStatus::INVAL => HttpCacheError::InvalidBackend,
            // This case is specifically for streaming the body, which is the only place it's expected
            FastlyStatus::BADF => HttpCacheError::InvalidOperation,
            other => HttpCacheError::Other(other),
        }
    }
}

impl HttpCacheError {
    pub fn is_unsupported(&self) -> bool {
        matches!(self, HttpCacheError::Unsupported)
    }
}

#[derive(Debug, Default)]
pub struct LookupOptions {
    pub override_key: Option<CacheKey>,
    pub backend_name: String,
}

impl LookupOptions {
    fn as_abi(&self) -> (sys::HttpCacheLookupOptionsMask, sys::HttpCacheLookupOptions) {
        use sys::HttpCacheLookupOptionsMask as Mask;

        let mut mask = Mask::empty();
        let (override_key_ptr, override_key_len) = if let Some(v) = &self.override_key {
            mask.insert(Mask::OVERRIDE_KEY);
            (v.as_ptr(), v.len())
        } else {
            (ptr::null(), 0)
        };
        let (backend_name_ptr, backend_name_len) =
            (self.backend_name.as_ptr(), self.backend_name.len());
        mask.insert(Mask::BACKEND_NAME);
        let options = sys::HttpCacheLookupOptions {
            override_key_ptr,
            override_key_len,
            backend_name_ptr,
            backend_name_len,
        };
        (mask, options)
    }
}

#[derive(Debug, Default, Clone)]
pub(crate) struct WriteOptions {
    pub max_age: Duration,
    pub vary_rule_abi: String,
    pub initial_age: Duration,
    pub stale_while_revalidate: Duration,
    pub surrogate_keys_abi: String,
    pub length: Option<u64>,
    pub sensitive_data: bool,
}

fn duration_to_u64_ns(dur: Duration) -> u64 {
    u64::try_from(dur.as_nanos()).unwrap_or(u64::MAX)
}

impl WriteOptions {
    fn as_abi(&self) -> (sys::HttpCacheWriteOptionsMask, sys::HttpCacheWriteOptions) {
        use sys::HttpCacheWriteOptionsMask as Mask;

        let mut mask = Mask::VARY_RULE
            | Mask::INITIAL_AGE_NS
            | Mask::STALE_WHILE_REVALIDATE_NS
            | Mask::SURROGATE_KEYS;

        if self.sensitive_data {
            mask.insert(Mask::SENSITIVE_DATA);
        }

        let length = if let Some(v) = self.length {
            mask.insert(Mask::LENGTH);
            v
        } else {
            0
        };

        let options = sys::HttpCacheWriteOptions {
            max_age_ns: duration_to_u64_ns(self.max_age),
            vary_rule_ptr: self.vary_rule_abi.as_ptr(),
            vary_rule_len: self.vary_rule_abi.len(),
            initial_age_ns: duration_to_u64_ns(self.initial_age),
            stale_while_revalidate_ns: duration_to_u64_ns(self.stale_while_revalidate),
            surrogate_keys_ptr: self.surrogate_keys_abi.as_ptr(),
            surrogate_keys_len: self.surrogate_keys_abi.len(),
            length,
        };
        (mask, options)
    }
}

pub fn is_request_cacheable(req_handle: &RequestHandle) -> Result<bool, HttpCacheError> {
    let mut is_cacheable_out = 0;
    unsafe { sys::is_request_cacheable(req_handle.as_u32(), &mut is_cacheable_out) }.result()?;
    Ok(is_cacheable_out == 1)
}

pub fn transaction_lookup(
    req_handle: &RequestHandle,
    options: &LookupOptions,
) -> Result<HttpCacheHandle, HttpCacheError> {
    let mut cache_handle_out = HttpCacheHandle::INVALID;
    let (options_mask, options) = options.as_abi();
    unsafe {
        sys::transaction_lookup(
            req_handle.as_u32(),
            options_mask,
            &options,
            cache_handle_out.as_abi_mut(),
        )
    }
    .result()?;
    Ok(cache_handle_out)
}

#[derive(Debug)]
pub struct HttpCacheHandle {
    cache_handle: sys::HttpCacheHandle,
}

impl Drop for HttpCacheHandle {
    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 HttpCacheHandle {
    #[cfg_attr(
        not(target_env = "p1"),
        deprecated(
            since = "0.11.6",
            note = "This code will need to be updated for wasip2."
        )
    )]
    const INVALID: Self = HttpCacheHandle {
        cache_handle: sys::INVALID_HTTP_CACHE_HANDLE,
    };

    fn is_invalid(&self) -> bool {
        self.cache_handle == sys::INVALID_HTTP_CACHE_HANDLE
    }

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

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

    pub fn transaction_insert(
        &self,
        resp_handle: ResponseHandle,
        options: &WriteOptions,
    ) -> Result<StreamingBodyHandle, HttpCacheError> {
        let mut body_handle_out = BodyHandle::INVALID;
        let (options_mask, options) = options.as_abi();
        unsafe {
            sys::transaction_insert(
                self.as_abi(),
                resp_handle.into_u32(),
                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,
        resp_handle: ResponseHandle,
        options: &WriteOptions,
    ) -> Result<(StreamingBodyHandle, HttpCacheHandle), HttpCacheError> {
        let mut body_handle_out = BodyHandle::INVALID;
        let mut cache_handle_out = HttpCacheHandle::INVALID;
        let (options_mask, options) = options.as_abi();
        unsafe {
            sys::transaction_insert_and_stream_back(
                self.as_abi(),
                resp_handle.into_u32(),
                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,
        resp_handle: ResponseHandle,
        options: &WriteOptions,
    ) -> Result<(), HttpCacheError> {
        let (options_mask, options) = options.as_abi();
        unsafe {
            sys::transaction_update(
                self.as_abi(),
                resp_handle.into_u32(),
                options_mask,
                &options,
            )
        }
        .result()
        .map_err(Into::into)
    }

    pub fn transaction_update_and_return_fresh(
        &self,
        resp_handle: ResponseHandle,
        options: &WriteOptions,
    ) -> Result<HttpCacheHandle, HttpCacheError> {
        let mut cache_handle_out = HttpCacheHandle::INVALID;
        let (options_mask, options) = options.as_abi();
        unsafe {
            sys::transaction_update_and_return_fresh(
                self.as_abi(),
                resp_handle.into_u32(),
                options_mask,
                &options,
                cache_handle_out.as_abi_mut(),
            )
        }
        .result()?;
        Ok(cache_handle_out)
    }

    pub fn transaction_record_not_cacheable(
        &self,
        max_age: Duration,
        vary_rule_abi: &str,
    ) -> Result<(), HttpCacheError> {
        let options_mask = sys::HttpCacheWriteOptionsMask::VARY_RULE;
        let options = sys::HttpCacheWriteOptions {
            max_age_ns: duration_to_u64_ns(max_age),
            vary_rule_ptr: vary_rule_abi.as_ptr(),
            vary_rule_len: vary_rule_abi.len(),
            initial_age_ns: 0,
            stale_while_revalidate_ns: 0,
            surrogate_keys_ptr: std::ptr::null(),
            surrogate_keys_len: 0,
            length: 0,
        };
        unsafe { sys::transaction_record_not_cacheable(self.as_abi(), options_mask, &options) }
            .result()
            .map_err(Into::into)
    }

    pub fn transaction_abandon(&self) -> Result<(), HttpCacheError> {
        unsafe { sys::transaction_abandon(self.as_abi()) }
            .result()
            .map_err(Into::into)
    }

    /// 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<(), HttpCacheError> {
        // 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()
            .map_err(Into::into)
    }

    pub fn get_suggested_backend_request(&self) -> Result<RequestHandle, HttpCacheError> {
        let mut req_handle_out = RequestHandle::INVALID;
        unsafe { sys::get_suggested_backend_request(self.as_abi(), req_handle_out.as_u32_mut()) }
            .result()?;
        Ok(req_handle_out)
    }

    pub fn get_suggested_cache_options(&self, resp_handle: &ResponseHandle) -> WriteOptions {
        use sys::HttpCacheWriteOptionsMask as Mask;

        // Note that `all()` means all bits that are defined in the mask type, not 0xFFFFFFFF
        let wanted_mask = Mask::all();
        let mut vary_rule_buf = Vec::with_capacity(INITIAL_BUF_SIZE);
        let mut surrogate_keys_buf = Vec::with_capacity(INITIAL_BUF_SIZE);
        let mut guest_supplied_pointers = sys::HttpCacheWriteOptions {
            max_age_ns: 0, // unused
            vary_rule_ptr: vary_rule_buf.as_mut_ptr(),
            vary_rule_len: vary_rule_buf.capacity(),
            initial_age_ns: 0,            // unused
            stale_while_revalidate_ns: 0, // unused
            surrogate_keys_ptr: surrogate_keys_buf.as_mut_ptr(),
            surrogate_keys_len: surrogate_keys_buf.capacity(),
            length: 0, // unused
        };
        let mut options_mask_out = Mask::empty();
        let mut options_out = sys::HttpCacheWriteOptions {
            max_age_ns: 0,
            vary_rule_ptr: ptr::null_mut(),
            vary_rule_len: 0,
            initial_age_ns: 0,
            stale_while_revalidate_ns: 0,
            surrogate_keys_ptr: ptr::null_mut(),
            surrogate_keys_len: 0,
            length: 0,
        };
        let mut status = unsafe {
            sys::get_suggested_cache_options(
                self.as_abi(),
                resp_handle.as_u32(),
                wanted_mask,
                &guest_supplied_pointers,
                &mut options_mask_out,
                &mut options_out,
            )
        };
        if let FastlyStatus::BUFLEN = status {
            if options_mask_out.contains(Mask::VARY_RULE)
                && options_out.vary_rule_len > vary_rule_buf.len()
            {
                vary_rule_buf.reserve_exact(options_out.vary_rule_len);
                guest_supplied_pointers.vary_rule_ptr = vary_rule_buf.as_mut_ptr();
                guest_supplied_pointers.vary_rule_len = options_out.vary_rule_len;
            }
            if options_mask_out.contains(Mask::SURROGATE_KEYS)
                && options_out.surrogate_keys_len > surrogate_keys_buf.len()
            {
                surrogate_keys_buf.reserve_exact(options_out.surrogate_keys_len);
                guest_supplied_pointers.surrogate_keys_ptr = surrogate_keys_buf.as_mut_ptr();
                guest_supplied_pointers.surrogate_keys_len = options_out.surrogate_keys_len;
            }
            // reset the output flags before the second call
            options_mask_out = Mask::empty();
            status = unsafe {
                sys::get_suggested_cache_options(
                    self.as_abi(),
                    resp_handle.as_u32(),
                    wanted_mask,
                    &guest_supplied_pointers,
                    &mut options_mask_out,
                    &mut options_out,
                )
            };
        }
        if status.is_err() {
            panic!(
                "get_suggested_cache options unexpectedly failed: {:?}",
                status
            )
        }
        let vary_rule_abi = {
            unsafe { vary_rule_buf.set_len(options_out.vary_rule_len) };
            String::from_utf8(vary_rule_buf).expect("host should only return UTF-8")
        };
        let surrogate_keys_abi = {
            unsafe { surrogate_keys_buf.set_len(options_out.surrogate_keys_len) };
            String::from_utf8(surrogate_keys_buf).expect("host should only return UTF-8")
        };
        let length = if options_mask_out.contains(Mask::LENGTH) {
            Some(options_out.length)
        } else {
            None
        };
        WriteOptions {
            max_age: Duration::from_nanos(options_out.max_age_ns),
            vary_rule_abi,
            initial_age: Duration::from_nanos(options_out.initial_age_ns),
            stale_while_revalidate: Duration::from_nanos(options_out.stale_while_revalidate_ns),
            surrogate_keys_abi,
            length,
            sensitive_data: options_mask_out.contains(Mask::SENSITIVE_DATA),
        }
    }

    pub fn prepare_response_for_storage(
        &self,
        resp_handle: &mut ResponseHandle,
    ) -> Result<HttpStorageAction, HttpCacheError> {
        let mut resp_handle_out = ResponseHandle::INVALID;
        let mut storage_action_out = sys::HttpStorageAction::DoNotStore;
        unsafe {
            sys::prepare_response_for_storage(
                self.as_abi(),
                resp_handle.as_u32(),
                &mut storage_action_out,
                resp_handle_out.as_u32_mut(),
            )
        }
        .result()?;
        *resp_handle = resp_handle_out;
        Ok(storage_action_out)
    }

    pub fn get_found_response(&self, was_hit: bool) -> Result<Response, HttpCacheError> {
        let mut resp_handle_out = ResponseHandle::INVALID;
        let mut body_handle_out = BodyHandle::INVALID;
        unsafe {
            sys::get_found_response(
                self.as_abi(),
                // transform_for_client = true:
                1,
                resp_handle_out.as_u32_mut(),
                body_handle_out.as_u32_mut(),
            )
        }
        .result()?;

        let mut resp = Response::from_handles(resp_handle_out, body_handle_out);
        resp.metadata.cache_options = Some(WriteOptions {
            max_age: Duration::from_nanos(
                self.get_max_age_ns().expect("cache options are present"),
            ),
            vary_rule_abi: self.get_vary_rule_abi().expect("cache options are present"),
            initial_age: Duration::from_nanos(
                self.get_age_ns().expect("cache options are present"),
            ),
            stale_while_revalidate: Duration::from_nanos(
                self.get_stale_while_revalidate_ns()
                    .expect("cache options are present"),
            ),
            surrogate_keys_abi: self
                .get_surrogate_keys_abi()
                .expect("cache options are present"),
            length: self.get_length(),
            sensitive_data: self
                .get_sensitive_data()
                .expect("cache options are present"),
        });
        resp.metadata.cache_storage_action = None;
        resp.metadata.cache_hits = self.get_hits().filter(|_| was_hit);
        Ok(resp)
    }

    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 must_insert_or_update(&self) -> bool {
        self.get_state()
            .contains(CacheLookupState::MUST_INSERT_OR_UPDATE)
    }

    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 fn get_sensitive_data(&self) -> Option<bool> {
        let mut is_sensitive_out = 0;
        let status = unsafe { sys::get_sensitive_data(self.as_abi(), &mut is_sensitive_out) };
        match status {
            FastlyStatus::OK => Some(is_sensitive_out == 1),
            FastlyStatus::NONE => None,
            status => {
                // any other errors are an SDK bug; panic
                panic!("sys::get_sensitive_data failed with {status:?}");
            }
        }
    }

    pub fn get_surrogate_keys_abi(&self) -> Option<String> {
        let mut surrogate_keys_buf = Vec::with_capacity(INITIAL_BUF_SIZE);
        let mut nwritten_out = 0;
        let mut status = unsafe {
            sys::get_surrogate_keys(
                self.as_abi(),
                surrogate_keys_buf.as_mut_ptr(),
                surrogate_keys_buf.capacity(),
                &mut nwritten_out,
            )
        };
        if status == FastlyStatus::BUFLEN {
            surrogate_keys_buf.reserve_exact(nwritten_out);
            status = unsafe {
                sys::get_surrogate_keys(
                    self.as_abi(),
                    surrogate_keys_buf.as_mut_ptr(),
                    surrogate_keys_buf.capacity(),
                    &mut nwritten_out,
                )
            };
        }
        match status {
            FastlyStatus::OK => {
                unsafe { surrogate_keys_buf.set_len(nwritten_out) };
                Some(String::from_utf8(surrogate_keys_buf).expect("host should only return UTF-8"))
            }
            FastlyStatus::NONE => None,
            // any other errors are an SDK bug; panic
            _ => panic!("sys::get_surrogate_keys_abi failed with {status:?}"),
        }
    }

    pub fn get_vary_rule_abi(&self) -> Option<String> {
        let mut vary_rule_buf = Vec::with_capacity(INITIAL_BUF_SIZE);
        let mut nwritten_out = 0;
        let mut status = unsafe {
            sys::get_vary_rule(
                self.as_abi(),
                vary_rule_buf.as_mut_ptr(),
                vary_rule_buf.capacity(),
                &mut nwritten_out,
            )
        };
        if status == FastlyStatus::BUFLEN {
            vary_rule_buf.reserve_exact(nwritten_out);
            status = unsafe {
                sys::get_vary_rule(
                    self.as_abi(),
                    vary_rule_buf.as_mut_ptr(),
                    vary_rule_buf.capacity(),
                    &mut nwritten_out,
                )
            };
        }
        match status {
            FastlyStatus::OK => {
                unsafe { vary_rule_buf.set_len(nwritten_out) };
                Some(String::from_utf8(vary_rule_buf).expect("host should only return UTF-8"))
            }
            FastlyStatus::NONE => None,
            // any other errors are an SDK bug; panic
            _ => panic!("sys::get_vary_rule_abi failed with {status:?}"),
        }
    }
}