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
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
//! HTTP requests.

use self::handle::RequestHandle;
use super::body::{self, Body, StreamingBody};
use super::response::{handles_to_response, FastlyResponseMetadata, Response};
use crate::backend::Backend;
use crate::convert::{Borrowable, ToBackend, ToHeaderName, ToHeaderValue, ToMethod, ToUrl};
use crate::error::{ensure, BufferSizeError, Error};
use crate::handle::BodyHandle;
use crate::limits::{self, RequestLimits};
use fastly_shared::CacheOverride;
use http::header::{HeaderName, HeaderValue};
use http::{HeaderMap, Method, Version};
use mime::Mime;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::fmt;
use std::io::BufRead;
use std::net::IpAddr;
use thiserror::Error;
use url::Url;

pub use pending::{select, PendingRequest, PollResult};

#[macro_use]
mod macros;

pub(crate) mod handle;
pub(crate) mod pending;

/// An HTTP request, including body, headers, method, and URL.
///
/// # Getting the client request
///
/// Call [`Request::from_client()`] to get the client request being handled by this execution of the
/// Compute@Edge program.
///
/// # Creation and conversion
///
/// New requests can be created programmatically with [`Request::new()`]. In addition, there are
/// convenience constructors like [`Request::get()`] which automatically select the appropriate
/// method.
///
/// For interoperability with other Rust libraries, [`Request`] can be converted to and from the
/// [`http`] crate's [`http::Request`] type using the [`From`][`Self::from()`] and
/// [`Into`][`Self::into()`] traits.
///
/// # Sending backend requests
///
/// Requests can be sent to a backend in blocking or asynchronous fashion using
/// [`send()`][`Self::send()`], [`send_async()`][`Self::send_async()`], or
/// [`send_async_streaming()`][`Self::send_async_streaming()`].
///
/// # Builder-style methods
///
/// [`Request`] can be used as a
/// [builder](https://doc.rust-lang.org/1.0.0/style/ownership/builders.html), allowing requests to
/// be constructed and used through method chaining. Methods with the `with_` name prefix, such as
/// [`with_header()`][`Self::with_header()`], return `Self` to allow chaining. The builder style is
/// typically most useful when constructing and using a request in a single expression. For example:
///
/// ```no_run
/// # use fastly::{Error, Request};
/// # fn f() -> Result<(), Error> {
/// Request::get("https://example.com")
///     .with_header("my-header", "hello!")
///     .with_header("my-other-header", "Здравствуйте!")
///     .send("example_backend")?;
/// # Ok(()) }
/// ```
///
/// # Setter methods
///
/// Setter methods, such as [`set_header()`][`Self::set_header()`], are prefixed by `set_`, and can
/// be used interchangeably with the builder-style methods, allowing you to mix and match styles
/// based on what is most convenient for your program. Setter methods tend to work better than
/// builder-style methods when constructing a request involves conditional branches or loops. For
/// example:
///
/// ```no_run
/// # use fastly::{Error, Request};
/// # fn f(needs_translation: bool) -> Result<(), Error> {
/// let mut req = Request::get("https://example.com").with_header("my-header", "hello!");
/// if needs_translation {
///     req.set_header("my-other-header", "Здравствуйте!");
/// }
/// req.send("example_backend")?;
/// # Ok(()) }
/// ```
#[derive(Debug)]
pub struct Request {
    version: Version,
    method: Method,
    url: Url,
    headers: HeaderMap,
    body: Option<Body>,
    cache_override: CacheOverride,
    is_from_client: bool,
}

impl Request {
    /// Get the client request being handled by this execution of the Compute@Edge program.
    ///
    /// # Panics
    ///
    /// This method panics if the client request has already been retrieved by this method,
    /// [`Request::try_from_client()`], or by [the low-level handle API][`crate::handle`].
    ///
    /// If the request exceeds the limits specified by [`RequestLimits`], this method sends an empty
    /// response with a `400 BAD REQUEST` HTTP status to the client, and then panics. Use
    /// [`try_from_client()`][`Self::try_from_client()`] if you want to explicitly handle these
    /// errors, for example by returning a customized error page.
    pub fn from_client() -> Request {
        Request::try_from_client()
            .unwrap_or_else(|_| panic_with_status!(crate::http::StatusCode::BAD_REQUEST))
    }

    /// Get the client request being handled by this execution of the Compute@Edge program, or an
    /// error if the request exceeds the limits specified by [`RequestLimits`].
    ///
    /// # Panics
    ///
    /// This method panics if the client request has already been retrieved by this method,
    /// [`Request::from_client()`], or by [the low-level handle API][`crate::handle`].
    pub fn try_from_client() -> Result<Request, BufferSizeError> {
        let (req_handle, body_handle) = self::handle::client_request_and_body();
        Request::from_handles(req_handle, Some(body_handle))
    }

    /// Return `true` if this request is from the client of this execution of the Compute@Edge
    /// program.
    pub fn is_from_client(&self) -> bool {
        self.is_from_client
    }

    /// Create a new request with the given method and URL, no headers, and an empty body.
    ///
    /// # Argument type conversion
    ///
    /// The method and URL arguments can be any types that implement [`ToMethod`] and [`ToUrl`],
    /// respectively. See those traits for details on which types can be used and when panics may
    /// arise during conversion.
    pub fn new(method: impl ToMethod, url: impl ToUrl) -> Self {
        Self {
            version: Version::HTTP_11,
            method: method.into_owned(),
            url: url.into_owned(),
            headers: HeaderMap::new(),
            body: None,
            cache_override: CacheOverride::default(),
            is_from_client: false,
        }
    }

    /// Make a new request with the same method, url, headers, and version of this request, but no
    /// body.
    ///
    /// If you also need to clone the request body, use
    /// [`clone_with_body()`][`Self::clone_with_body()`]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let original = Request::post("https://example.com")
    ///     .with_header("hello", "world!")
    ///     .with_body("hello");
    /// let new = original.clone_without_body();
    /// assert_eq!(original.get_method(), new.get_method());
    /// assert_eq!(original.get_url(), new.get_url());
    /// assert_eq!(original.get_header("hello"), new.get_header("hello"));
    /// assert_eq!(original.get_version(), new.get_version());
    /// assert!(original.has_body());
    /// assert!(!new.has_body());
    /// ```
    pub fn clone_without_body(&self) -> Request {
        Self {
            version: self.version,
            method: self.method.clone(),
            url: self.url.clone(),
            headers: self.headers.clone(),
            body: None,
            cache_override: self.cache_override.clone(),
            is_from_client: self.is_from_client,
        }
    }

    /// Clone this request by reading in its body, and then writing the same body to the original
    /// and the cloned request.
    ///
    /// This method requires mutable access to this request because reading from and writing to the
    /// body can involve an HTTP connection.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/clones-body.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut original = Request::post("https://example.com")
    ///     .with_header("hello", "world!")
    ///     .with_body("hello");
    /// let mut new = original.clone_with_body();
    /// assert_eq!(original.get_method(), new.get_method());
    /// assert_eq!(original.get_url(), new.get_url());
    /// assert_eq!(original.get_header("hello"), new.get_header("hello"));
    /// assert_eq!(original.get_version(), new.get_version());
    /// assert_eq!(original.take_body_bytes(), new.take_body_bytes());
    /// ```
    pub fn clone_with_body(&mut self) -> Request {
        let mut new_req = self.clone_without_body();
        if self.has_body() {
            for chunk in self.take_body().read_chunks(4096) {
                let chunk = chunk.expect("can read body chunk");
                new_req.get_body_mut().write_bytes(&chunk);
                self.get_body_mut().write_bytes(&chunk);
            }
        }
        new_req
    }

    /// Create a new `GET` [`Request`] with the given URL, no headers, and an empty body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/url-argument.md")
    )]
    pub fn get(url: impl ToUrl) -> Self {
        Self::new(Method::GET, url)
    }

    /// Create a new `HEAD` [`Request`] with the given URL, no headers, and an empty body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/url-argument.md")
    )]
    pub fn head(url: impl ToUrl) -> Self {
        Self::new(Method::HEAD, url)
    }

    /// Create a new `POST` [`Request`] with the given URL, no headers, and an empty body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/url-argument.md")
    )]
    pub fn post(url: impl ToUrl) -> Self {
        Self::new(Method::POST, url)
    }

    /// Create a new `PUT` [`Request`] with the given URL, no headers, and an empty body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/url-argument.md")
    )]
    pub fn put(url: impl ToUrl) -> Self {
        Self::new(Method::PUT, url)
    }

    /// Create a new `DELETE` [`Request`] with the given URL, no headers, and an empty body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/url-argument.md")
    )]
    pub fn delete(url: impl ToUrl) -> Self {
        Self::new(Method::DELETE, url)
    }

    /// Create a new `CONNECT` [`Request`] with the given URL, no headers, and an empty body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/url-argument.md")
    )]
    pub fn connect(url: impl ToUrl) -> Self {
        Self::new(Method::CONNECT, url)
    }

    /// Create a new `OPTIONS` [`Request`] with the given URL, no headers, and an empty body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/url-argument.md")
    )]
    pub fn options(url: impl ToUrl) -> Self {
        Self::new(Method::OPTIONS, url)
    }

    /// Create a new `TRACE` [`Request`] with the given URL, no headers, and an empty body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/url-argument.md")
    )]
    pub fn trace(url: impl ToUrl) -> Self {
        Self::new(Method::TRACE, url)
    }

    /// Create a new `PATCH` [`Request`] with the given URL, no headers, and an empty body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/url-argument.md")
    )]
    pub fn patch(url: impl ToUrl) -> Self {
        Self::new(Method::PATCH, url)
    }

    /// Send the request to the given backend server, and return once the response headers have been
    /// received, or an error occurs.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/backend-argument.md")
    )]
    ///
    /// # Panics
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/panics-responselimits.md")
    )]
    ///
    /// # Examples
    ///
    /// Sending the client request to a backend without modification:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let backend_resp = Request::from_client().send("example_backend").expect("request succeeds");
    /// assert!(backend_resp.get_status().is_success());
    /// ```
    ///
    /// Sending a synthetic request:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let backend_resp = Request::get("https://example.com")
    ///     .send("example_backend")
    ///     .expect("request succeeds");
    /// assert!(backend_resp.get_status().is_success());
    /// ```
    pub fn send(self, backend: impl ToBackend) -> Result<Response, SendError> {
        let backend = backend.into_owned();
        let (req_handle, req_body_handle, sent_req) = self.prepare_handles(&backend)?;
        let (resp_handle, resp_body_handle) = try_with_req!(
            backend.name(),
            sent_req,
            req_handle.send(req_body_handle, backend.name())
        );
        handles_to_response(
            resp_handle,
            resp_body_handle,
            FastlyResponseMetadata::new(backend, sent_req),
        )
    }

    /// Begin sending the request to the given backend server, and return a [`PendingRequest`] that
    /// can yield the backend response or an error.
    ///
    /// This method returns as soon as the request begins sending to the backend, and transmission
    /// of the request body and headers will continue in the background.
    ///
    /// This method allows for sending more than one request at once and receiving their responses
    /// in arbitrary orders. See [`PendingRequest`] for more details on how to wait on, poll, or
    /// select between pending requests.
    ///
    /// This method is also useful for sending requests where the response is unimportant, but the
    /// request may take longer than the Compute@Edge program is able to run, as the request will
    /// continue sending even after the program that intitiated it exits.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/backend-argument.md")
    )]
    ///
    /// # Examples
    ///
    /// Sending a request to two backends and returning whichever response finishes first:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let backend_resp_1 = Request::get("https://example.com/")
    ///     .send_async("example_backend_1")
    ///     .expect("request 1 begins sending");
    /// let backend_resp_2 = Request::get("https://example.com/")
    ///     .send_async("example_backend_2")
    ///     .expect("request 2 begins sending");
    /// let (resp, _) = fastly::http::request::select(vec![backend_resp_1, backend_resp_2]);
    /// resp.expect("request succeeds").send_to_client();
    /// ```
    ///
    /// Sending a long-running request and ignoring its result so that the program can exit before
    /// it completes:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// # let some_large_file = vec![0u8];
    /// let _ = Request::post("https://example.com")
    ///     .with_body(some_large_file)
    ///     .send_async("example_backend");
    /// ```
    pub fn send_async(self, backend: impl ToBackend) -> Result<PendingRequest, SendError> {
        let backend = backend.into_owned();
        let (req_handle, req_body_handle, sent_req) = self.prepare_handles(&backend)?;
        let pending_req_handle = try_with_req!(
            backend.name(),
            sent_req,
            req_handle.send_async(req_body_handle, backend.name())
        );
        let pending_req = PendingRequest::new(
            pending_req_handle,
            FastlyResponseMetadata::new(backend, sent_req),
        );
        Ok(pending_req)
    }

    /// Begin sending the request to the given backend server, and return a [`PendingRequest`] that
    /// can yield the backend response or an error along with a [`StreamingBody`] that can accept
    /// further data to send.
    ///
    /// This method is most useful for programs that do some sort of processing or inspection of a
    /// potentially-large client request body. Streaming allows the program to operate on small
    /// parts of the body rather than having to read it all into memory at once.
    ///
    /// This method returns as soon as the request begins sending to the backend, and transmission
    /// of the request body and headers will continue in the background.
    ///
    /// Note that the backend connection is only closed once the [`StreamingBody`] is dropped. You
    /// can explicitly drop the body once finished to avoid holding the connection open longer than
    /// necessary. The [`PendingRequest`] will not yield a [`Response`] until the [`StreamingBody`]
    /// is closed.
    ///
    /// # Examples
    ///
    /// Count the number of lines in a UTF-8 client request body while sending it to the backend:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// use std::io::BufRead;
    ///
    /// let mut req = Request::from_client();
    /// // Take the body so we can iterate through its lines later
    /// let req_body = req.take_body();
    /// // Start sending the client request to the client with a now-empty body
    /// let (mut backend_body, pending_req) = req
    ///     .send_async_streaming("example_backend")
    ///     .expect("request begins sending");
    ///
    /// let mut num_lines = 0;
    /// for line in req_body.lines() {
    ///     let line = line.unwrap();
    ///     num_lines += 1;
    ///     // Write the line to the streaming backend body
    ///     backend_body.write_str(&line);
    /// }
    /// // Drop the streaming body to allow the backend connection to close
    /// drop(backend_body);
    ///
    /// log::debug!("client request body contained {} lines", num_lines);
    /// ```
    pub fn send_async_streaming(
        self,
        backend: impl ToBackend,
    ) -> Result<(StreamingBody, PendingRequest), SendError> {
        let backend = backend.into_owned();
        let (req_handle, req_body_handle, sent_req) = self.prepare_handles(&backend)?;
        let (streaming_body_handle, pending_req_handle) = try_with_req!(
            backend.name(),
            sent_req,
            req_handle.send_async_streaming(req_body_handle, backend.name())
        );
        let pending_req = PendingRequest::new(
            pending_req_handle,
            FastlyResponseMetadata::new(backend, sent_req),
        );
        Ok((streaming_body_handle.into(), pending_req))
    }

    /// A helper function for decomposing a [`Request`] into handles for use in hostcalls.
    ///
    /// Note that in addition to the [`RequestHandle`] and [`BodyHandle`], the tuple returned also
    /// includes a copy of the original request so that metadata about the request can be inspected
    /// later using the `FastlyResponseMetadata` extension.
    ///
    /// This will return an error if the backend name is invalid, or if the request does not have a
    /// valid URI.
    fn prepare_handles(
        mut self,
        backend: impl ToBackend,
    ) -> Result<(RequestHandle, BodyHandle, Self), SendError> {
        // First, validate the request.
        if let Err(e) = validate_request(&self) {
            return Err(SendError::new(
                backend.into_borrowable().as_ref().name(),
                self,
                SendErrorCause::Generic(e),
            ));
        }
        let (req_handle, body_handle) = self.to_handles();
        Ok((
            req_handle,
            // TODO ACF 2020-11-30: it'd be nice to change the ABI so that body handles were
            // optional to save a hostcall for many requests
            body_handle.unwrap_or_else(|| BodyHandle::new()),
            self,
        ))
    }

    /// Builder-style equivalent of [`set_body()`][`Self::set_body()`].
    pub fn with_body(mut self, body: impl Into<Body>) -> Self {
        self.set_body(body);
        self
    }

    /// Returns `true` if this request has a body.
    pub fn has_body(&self) -> bool {
        self.body.is_some()
    }

    /// Get a mutable reference to the body of this request.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/creates-empty-body.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// use std::io::Write;
    ///
    /// let mut req = Request::post("https://example.com").with_body("hello,");
    /// write!(req.get_body_mut(), " world!").unwrap();
    /// assert_eq!(&req.into_body_str(), "hello, world!");
    /// ```
    pub fn get_body_mut(&mut self) -> &mut Body {
        self.body.get_or_insert_with(|| Body::new())
    }

    /// Get a shared reference to the body of this request if it has one, otherwise return `None`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// use std::io::Write;
    ///
    /// let mut req = Request::post("https://example.com");
    /// assert!(req.try_get_body_mut().is_none());
    ///
    /// req.set_body("hello,");
    /// write!(req.try_get_body_mut().expect("body now exists"), " world!").unwrap();
    /// assert_eq!(&req.into_body_str(), "hello, world!");
    /// ```
    pub fn try_get_body_mut(&mut self) -> Option<&mut Body> {
        self.body.as_mut()
    }

    /// Get a prefix of this request's body containing up to the given number of bytes.
    ///
    /// See [`Body::get_prefix_mut()`] for details.
    pub fn get_body_prefix_mut(&mut self, length: usize) -> body::Prefix {
        self.get_body_mut().get_prefix_mut(length)
    }

    /// Get a prefix of this request's body as a string containing up to the given number of bytes.
    ///
    /// See [`Body::get_prefix_str_mut()`] for details.
    ///
    /// # Panics
    ///
    /// If the prefix contains invalid UTF-8 bytes, this function will panic. The exception to this
    /// is if the bytes are invalid because a multi-byte codepoint is cut off by the requested
    /// prefix length. In this case, the invalid bytes are left off the end of the prefix.
    ///
    /// To explicitly handle the possibility of invalid UTF-8 bytes, use
    /// [`try_get_body_prefix_str_mut()`][`Self::try_get_body_prefix_str_mut()`], which returns an
    /// error on failure rather than panicking.
    pub fn get_body_prefix_str_mut(&mut self, length: usize) -> body::PrefixString {
        self.get_body_mut().get_prefix_str_mut(length)
    }

    /// Try to get a prefix of the body as a string containing up to the given number of bytes.
    ///
    /// See [`Body::try_get_prefix_str_mut()`] for details.
    pub fn try_get_body_prefix_str_mut(
        &mut self,
        length: usize,
    ) -> Result<body::PrefixString, std::str::Utf8Error> {
        self.get_body_mut().try_get_prefix_str_mut(length)
    }

    /// Set the given value as the request's body.
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/body-argument.md")
    )]
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/discards-body.md")
    )]
    pub fn set_body(&mut self, body: impl Into<Body>) {
        self.body = Some(body.into());
    }

    /// Take and return the body from this request.
    ///
    /// After calling this method, this request will no longer have a body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/creates-empty-body.md")
    )]
    pub fn take_body(&mut self) -> Body {
        self.body.take().unwrap_or_else(|| Body::new())
    }

    /// Take and return the body from this request if it has one, otherwise return `None`.
    ///
    /// After calling this method, this request will no longer have a body.
    pub fn try_take_body(&mut self) -> Option<Body> {
        self.body.take()
    }

    /// Append another [`Body`] to the body of this request without reading or writing any body
    /// contents.
    ///
    /// If this request does not have a body, the appended body is set as the request's body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/body-append-constant-time.md")
    )]
    ///
    /// This method should be used when combining bodies that have not necessarily been read yet,
    /// such as the body of the client. To append contents that are already in memory as strings or
    /// bytes, you should instead use [`get_body_mut()`][`Self::get_body_mut()`] to write the
    /// contents to the end of the body.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::post("https://example.com").with_body("hello! client says: ");
    /// req.append_body(Request::from_client().into_body());
    /// req.send("example_backend").unwrap();
    /// ```
    pub fn append_body(&mut self, other: Body) {
        if let Some(ref mut body) = &mut self.body {
            body.append(other);
        } else {
            self.body = Some(other);
        }
    }

    /// Consume the request and return its body as a byte vector.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/buffers-body-reqresp.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::post("https://example.com").with_body(b"hello, world!".to_vec());
    /// let bytes = req.into_body_bytes();
    /// assert_eq!(&bytes, b"hello, world!");
    pub fn into_body_bytes(mut self) -> Vec<u8> {
        self.take_body_bytes()
    }

    /// Consume the request and return its body as a string.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/buffers-body-reqresp.md")
    )]
    ///
    /// # Panics
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/panics-reqresp-intobody-utf8.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::post("https://example.com").with_body("hello, world!");
    /// let string = req.into_body_str();
    /// assert_eq!(&string, "hello, world!");
    /// ```
    pub fn into_body_str(mut self) -> String {
        self.take_body_str()
    }

    /// Consume the request and return its body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/creates-empty-body.md")
    )]
    pub fn into_body(self) -> Body {
        self.body.unwrap_or_else(|| Body::new())
    }

    /// Consume the request and return its body if it has one, otherwise return `None`.
    pub fn try_into_body(self) -> Option<Body> {
        self.body
    }

    /// Deprecated alias of [`with_body_text_plain()`][`Self::with_body_text_plain()`]
    #[deprecated(since = "0.7.0", note = "renamed to `Request::with_body_text_plain()`")]
    pub fn with_body_str(self, body: &str) -> Self {
        self.with_body_text_plain(body)
    }

    /// Builder-style equivalent of [`set_body_text_plain()`][`Self::set_body_text_plain()`].
    pub fn with_body_text_plain(mut self, body: &str) -> Self {
        self.set_body_text_plain(body);
        self
    }

    /// Deprecated alias of [`set_body_text_plain()`][`Self::set_body_text_plain()`]
    #[deprecated(since = "0.7.0", note = "renamed to `Request::set_body_text_plain()`")]
    pub fn set_body_str(&mut self, body: &str) {
        self.set_body_text_plain(body);
    }

    /// Set the given string as the request's body with content type `text/plain; charset=UTF-8`.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/discards-body.md")
    )]
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/sets-text-plain.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::post("https://example.com");
    /// req.set_body_text_plain("hello, world!");
    /// assert_eq!(req.get_content_type(), Some(fastly::mime::TEXT_PLAIN_UTF_8));
    /// assert_eq!(&req.into_body_str(), "hello, world!");
    /// ```
    pub fn set_body_text_plain(&mut self, body: &str) {
        self.body = Some(Body::from(body));
        self.set_content_type(mime::TEXT_PLAIN_UTF_8);
    }

    /// Builder-style equivalent of [`set_body_text_html()`][`Self::set_body_text_html()`].
    pub fn with_body_text_html(mut self, body: &str) -> Self {
        self.set_body_text_html(body);
        self
    }

    /// Set the given string as the request's body with content type `text/html; charset=UTF-8`.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/discards-body.md")
    )]
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/sets-text-html.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::post("https://example.com");
    /// req.set_body_text_html("<p>hello, world!</p>");
    /// assert_eq!(req.get_content_type(), Some(fastly::mime::TEXT_HTML_UTF_8));
    /// assert_eq!(&req.into_body_str(), "<p>hello, world!</p>");
    /// ```
    pub fn set_body_text_html(&mut self, body: &str) {
        self.body = Some(Body::from(body));
        self.set_content_type(mime::TEXT_HTML_UTF_8);
    }

    /// Take and return the body from this request as a string.
    ///
    /// After calling this method, this request will no longer have a body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/buffers-body-reqresp.md")
    )]
    ///
    /// # Panics
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/panics-reqresp-takebody-utf8.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::post("https://example.com").with_body("hello, world!");
    /// let string = req.take_body_str();
    /// assert!(req.try_take_body().is_none());
    /// assert_eq!(&string, "hello, world!");
    /// ```
    pub fn take_body_str(&mut self) -> String {
        if let Some(body) = self.try_take_body() {
            body.into_string()
        } else {
            String::new()
        }
    }

    /// Return a [`Lines`][`std::io::Lines`] iterator that reads the request body a line at a time.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::{Body, Request};
    /// use std::io::Write;
    ///
    /// fn remove_es(req: &mut Request) {
    ///     let mut no_es = Body::new();
    ///     for line in req.read_body_lines() {
    ///         writeln!(no_es, "{}", line.unwrap().replace("e", "")).unwrap();
    ///     }
    ///     req.set_body(no_es);
    /// }
    /// ```
    pub fn read_body_lines(&mut self) -> std::io::Lines<&mut Body> {
        self.get_body_mut().lines()
    }

    /// Builder-style equivalent of [`set_body_bytes()`][`Self::set_body_bytes()`].
    pub fn with_body_bytes(mut self, body: &[u8]) -> Self {
        self.set_body_bytes(body);
        self
    }

    /// Set the given bytes as the request's body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/discards-body.md")
    )]
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/sets-app-octet-stream.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::post("https://example.com");
    /// req.set_body_bytes(b"hello, world!");
    /// assert_eq!(req.get_content_type(), Some(fastly::mime::APPLICATION_OCTET_STREAM));
    /// assert_eq!(&req.into_body_bytes(), b"hello, world!");
    /// ```
    pub fn set_body_bytes(&mut self, body: &[u8]) {
        self.body = Some(Body::from(body));
        self.set_content_type(mime::APPLICATION_OCTET_STREAM);
    }

    /// Take and return the body from this request as a string.
    ///
    /// After calling this method, this request will no longer have a body.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/buffers-body-reqresp.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::post("https://example.com").with_body(b"hello, world!".to_vec());
    /// let bytes = req.take_body_bytes();
    /// assert!(req.try_take_body().is_none());
    /// assert_eq!(&bytes, b"hello, world!");
    /// ```
    pub fn take_body_bytes(&mut self) -> Vec<u8> {
        if let Some(body) = self.try_take_body() {
            body.into_bytes()
        } else {
            Vec::new()
        }
    }

    /// Return an iterator that reads the request body in chunks of at most the given number of
    /// bytes.
    ///
    /// If `chunk_size` does not evenly divide the length of the body, then the last chunk will not
    /// have length `chunk_size`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::{Body, Request};
    /// fn remove_0s(req: &mut Request) {
    ///     let mut no_0s = Body::new();
    ///     for chunk in req.read_body_chunks(4096) {
    ///         let mut chunk = chunk.unwrap();
    ///         chunk.retain(|b| *b != 0);
    ///         no_0s.write_bytes(&chunk);
    ///     }
    ///     req.set_body(no_0s);
    /// }
    /// ```
    pub fn read_body_chunks<'a>(
        &'a mut self,
        chunk_size: usize,
    ) -> impl Iterator<Item = Result<Vec<u8>, std::io::Error>> + 'a {
        self.get_body_mut().read_chunks(chunk_size)
    }

    /// Builder-style equivalent of [`set_body_json()`][Self::set_body_json()`].
    pub fn with_body_json(mut self, value: &impl Serialize) -> Result<Self, serde_json::Error> {
        self.set_body_json(value)?;
        Ok(self)
    }

    /// Convert the given value to JSON and set that JSON as the request's body.
    ///
    /// The given value must implement [`serde::Serialize`]. You can either implement that trait for
    /// your own custom type, or use [`serde_json::Value`] to create untyped JSON values. See
    /// [`serde_json`] for details.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/discards-body.md")
    )]
    ///
    /// # Content type
    ///
    /// This method sets the content type to `application/json`.
    ///
    /// # Errors
    ///
    /// This method returns [`serde_json::Error`] if serialization fails.
    ///
    /// # Examples
    ///
    /// Using a type that derives [`serde::Serialize`]:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// #[derive(serde::Serialize)]
    /// struct MyData {
    ///     name: String,
    ///     count: u64,
    /// }
    /// let my_data = MyData { name: "Computers".to_string(), count: 1024 };
    /// let mut req = Request::post("https://example.com");
    /// req.set_body_json(&my_data).unwrap();
    /// assert_eq!(req.get_content_type(), Some(fastly::mime::APPLICATION_JSON));
    /// assert_eq!(&req.into_body_str(), r#"{"name":"Computers","count":1024}"#);
    /// ```
    ///
    /// Using untyped JSON and the [`serde_json::json`] macro:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let my_data = serde_json::json!({
    ///     "name": "Computers",
    ///     "count": 1024,
    /// });
    /// let mut req = Request::post("https://example.com");
    /// req.set_body_json(&my_data).unwrap();
    /// assert_eq!(req.get_content_type(), Some(fastly::mime::APPLICATION_JSON));
    /// assert_eq!(&req.into_body_str(), r#"{"count":1024,"name":"Computers"}"#);
    /// ```
    pub fn set_body_json(&mut self, value: &impl Serialize) -> Result<(), serde_json::Error> {
        self.body = Some(Body::new());
        serde_json::to_writer(self.get_body_mut(), value)?;
        self.set_content_type(mime::APPLICATION_JSON);
        Ok(())
    }

    /// Take the request body and attempt to parse it as a JSON value.
    ///
    /// The return type must implement [`serde::Deserialize`] without any non-static lifetimes. You
    /// can either implement that trait for your own custom type, or use [`serde_json::Value`] to
    /// deserialize untyped JSON values. See [`serde_json`] for details.
    ///
    /// After calling this method, this request will no longer have a body.
    ///
    /// # Errors
    ///
    /// This method returns [`serde_json::Error`] if deserialization fails.
    ///
    /// # Examples
    ///
    /// Using a type that derives [`serde::de::DeserializeOwned`]:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// #[derive(serde::Deserialize)]
    /// struct MyData {
    ///     name: String,
    ///     count: u64,
    /// }
    /// let mut req = Request::post("https://example.com")
    ///     .with_body(r#"{"name":"Computers","count":1024}"#);
    /// let my_data = req.take_body_json::<MyData>().unwrap();
    /// assert_eq!(&my_data.name, "Computers");
    /// assert_eq!(my_data.count, 1024);
    /// ```
    ///
    /// Using untyped JSON with [`serde_json::Value`]:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let my_data = serde_json::json!({
    ///     "name": "Computers",
    ///     "count": 1024,
    /// });
    /// let mut req = Request::post("https://example.com")
    ///     .with_body(r#"{"name":"Computers","count":1024}"#);
    /// let my_data = req.take_body_json::<serde_json::Value>().unwrap();
    /// assert_eq!(my_data["name"].as_str(), Some("Computers"));
    /// assert_eq!(my_data["count"].as_u64(), Some(1024));
    /// ```
    pub fn take_body_json<T: DeserializeOwned>(&mut self) -> Result<T, serde_json::Error> {
        if let Some(body) = self.try_take_body() {
            serde_json::from_reader(body)
        } else {
            serde_json::from_reader(std::io::empty())
        }
    }

    /// Builder-style equivalent of [`set_body_form()`][`Self::set_body_form()`].
    pub fn with_body_form(
        mut self,
        value: &impl Serialize,
    ) -> Result<Self, serde_urlencoded::ser::Error> {
        self.set_body_form(value)?;
        Ok(self)
    }

    /// Convert the given value to `application/x-www-form-urlencoded` format and set that data as
    /// the request's body.
    ///
    /// The given value must implement [`serde::Serialize`]; see the trait documentation for
    /// details.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/discards-body.md")
    )]
    ///
    /// # Content type
    ///
    /// This method sets the content type to `application/x-www-form-urlencoded`.
    ///
    /// # Errors
    ///
    /// This method returns [`serde_urlencoded::ser::Error`] if serialization fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// #[derive(serde::Serialize)]
    /// struct MyData {
    ///     name: String,
    ///     count: u64,
    /// }
    /// let my_data = MyData { name: "Computers".to_string(), count: 1024 };
    /// let mut req = Request::post("https://example.com");
    /// req.set_body_form(&my_data).unwrap();
    /// assert_eq!(req.get_content_type(), Some(fastly::mime::APPLICATION_WWW_FORM_URLENCODED));
    /// assert_eq!(&req.into_body_str(), "name=Computers&count=1024");
    /// ```
    pub fn set_body_form(
        &mut self,
        value: &impl Serialize,
    ) -> Result<(), serde_urlencoded::ser::Error> {
        self.body = Some(Body::new());
        let s = serde_urlencoded::to_string(value)?;
        self.set_body(s);
        self.set_content_type(mime::APPLICATION_WWW_FORM_URLENCODED);
        Ok(())
    }

    /// Take the request body and attempt to parse it as a `application/x-www-form-urlencoded`
    /// formatted string.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/returns-deserializeowned.md")
    )]
    ///
    /// After calling this method, this request will no longer have a body.
    ///
    /// # Errors
    ///
    /// This method returns [`serde_urlencoded::de::Error`] if deserialization fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// #[derive(serde::Deserialize)]
    /// struct MyData {
    ///     name: String,
    ///     count: u64,
    /// }
    /// let mut req = Request::post("https://example.com").with_body("name=Computers&count=1024");
    /// let my_data = req.take_body_form::<MyData>().unwrap();
    /// assert_eq!(&my_data.name, "Computers");
    /// assert_eq!(my_data.count, 1024);
    /// ```
    pub fn take_body_form<T: DeserializeOwned>(
        &mut self,
    ) -> Result<T, serde_urlencoded::de::Error> {
        if let Some(body) = self.try_take_body() {
            serde_urlencoded::from_reader(body)
        } else {
            serde_urlencoded::from_reader(std::io::empty())
        }
    }

    /// Get the MIME type described by the request's
    /// [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type)
    /// header, or `None` if that header is absent or contains an invalid MIME type.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::post("https://example.com").with_body_text_plain("hello, world!");
    /// assert_eq!(req.get_content_type(), Some(fastly::mime::TEXT_PLAIN_UTF_8));
    /// ```
    pub fn get_content_type(&self) -> Option<Mime> {
        self.get_header_str(http::header::CONTENT_TYPE).map(|v| {
            v.parse()
                .unwrap_or_else(|_| panic!("invalid MIME type in Content-Type header: {}", v))
        })
    }

    /// Builder-style equivalent of [`set_content_type()`][`Self::set_content_type()`].
    pub fn with_content_type(mut self, mime: Mime) -> Self {
        self.set_content_type(mime);
        self
    }

    /// Set the MIME type described by the request's
    /// [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type)
    /// header.
    ///
    /// Any existing `Content-Type` header values will be overwritten.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::post("https://example.com").with_body("hello,world!");
    /// req.set_content_type(fastly::mime::TEXT_CSV_UTF_8);
    /// ```
    pub fn set_content_type(&mut self, mime: Mime) {
        self.set_header(http::header::CONTENT_TYPE, mime.as_ref())
    }

    /// Get the value of the request's
    /// [`Content-Length`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length)
    /// header, if it exists.
    pub fn get_content_length(&self) -> Option<usize> {
        self.get_header(http::header::CONTENT_LENGTH)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse().ok())
    }

    /// Returns whether the given header name is present in the request.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/header-name-argument.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::get("https://example.com").with_header("hello", "world!");
    /// assert!(req.contains_header("hello"));
    /// assert!(!req.contains_header("not-present"));
    /// ```
    pub fn contains_header(&self, name: impl ToHeaderName) -> bool {
        self.headers.contains_key(name.into_borrowable().as_ref())
    }

    /// Builder-style equivalent of [`set_header()`][`Self::set_header()`].
    pub fn with_header(mut self, name: impl ToHeaderName, value: impl ToHeaderValue) -> Self {
        self.set_header(name, value);
        self
    }

    /// Get the value of a header as a string, or `None` if the header is not present.
    ///
    /// If there are multiple values for the header, only one is returned, which may be any of the
    /// values. See [`get_header_all_str()`][`Self::get_header_all_str()`] if you need to get all of
    /// the values.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/header-name-argument.md")
    )]
    ///
    /// # Panics
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/panics-reqresp-header-utf8.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::get("https://example.com").with_header("hello", "world!");
    /// assert_eq!(req.get_header_str("hello"), Some("world"));
    /// ```
    pub fn get_header_str(&self, name: impl ToHeaderName) -> Option<&str> {
        let name = name.into_borrowable();
        if let Some(hdr) = self.get_header(name.as_ref()) {
            Some(
                hdr.to_str()
                    .unwrap_or_else(|_| panic!("non-UTF-8 HTTP header value for header: {}", name)),
            )
        } else {
            None
        }
    }

    /// Get the value of a header, or `None` if the header is not present.
    ///
    /// If there are multiple values for the header, only one is returned, which may be any of the
    /// values. See [`get_header_all()`][`Self::get_header_all()`] if you need to get all of the
    /// values.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/header-name-argument.md")
    )]
    ///
    /// # Examples
    ///
    /// Handling UTF-8 values explicitly:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// # use fastly::http::HeaderValue;
    /// let req = Request::get("https://example.com").with_header("hello", "world!");
    /// assert_eq!(req.get_header("hello"), Some(&HeaderValue::from_static("world")));
    /// ```
    ///
    /// Safely handling invalid UTF-8 values:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let invalid_utf8 = &"🐈".as_bytes()[0..3];
    /// let req = Request::get("https://example.com").with_header("hello", invalid_utf8);
    /// assert_eq!(req.get_header("hello").unwrap().as_bytes(), invalid_utf8);
    /// ```
    pub fn get_header(&self, name: impl ToHeaderName) -> Option<&HeaderValue> {
        self.headers.get(name.into_borrowable().as_ref())
    }

    /// Get all values of a header as strings, or an empty vector if the header is not present.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/header-name-argument.md")
    )]
    ///
    /// # Panics
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/panics-reqresp-headers-utf8.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::get("https://example.com")
    ///     .with_header("hello", "world!")
    ///     .with_header("hello", "universe!");
    /// let values = req.get_header_all_str("hello");
    /// assert_eq!(values.len(), 2);
    /// assert!(values.contains(&"world!"));
    /// assert!(values.contains(&"universe!"));
    /// ```
    pub fn get_header_all_str(&self, name: impl ToHeaderName) -> Vec<&str> {
        let name = name.into_borrowable();
        self.get_header_all(name.as_ref())
            .map(|v| {
                v.to_str()
                    .unwrap_or_else(|_| panic!("non-UTF-8 HTTP header value for header: {}", name))
            })
            .collect()
    }

    /// Get an iterator of all the values of a header.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/header-name-argument.md")
    )]
    ///
    /// # Examples
    ///
    /// You can turn the iterator into collection, like [`Vec`]:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// # use fastly::http::HeaderValue;
    /// let invalid_utf8 = &"🐈".as_bytes()[0..3];
    /// let req = Request::get("https://example.com")
    ///     .with_header("hello", "world!")
    ///     .with_header("hello", invalid_utf8);
    ///
    /// let values: Vec<&HeaderValue> = req.get_header_all("hello").collect();
    /// assert_eq!(values.len(), 2);
    /// assert!(values.contains(&&HeaderValue::from_static("world!")));
    /// assert!(values.contains(&&HeaderValue::from_bytes(invalid_utf8).unwrap()));
    /// ```
    ///
    /// You can use the iterator in a loop:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let invalid_utf8 = &"🐈".as_bytes()[0..3];
    /// let req = Request::get("https://example.com")
    ///     .with_header("hello", "world!")
    ///     .with_header("hello", invalid_utf8);
    ///
    /// for value in req.get_header_all("hello") {
    ///     if let Ok(s) = value.to_str() {
    ///         log::debug!("hello, {}", s);
    ///     } else {
    ///         log::debug!("hello, invalid UTF-8!");
    ///     }
    /// }
    /// ```
    pub fn get_header_all(&self, name: impl ToHeaderName) -> impl Iterator<Item = &HeaderValue> {
        self.headers.get_all(name.into_borrowable().as_ref()).iter()
    }

    /// Get all of the request's header names as strings, or an empty vector if no headers are
    /// present.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::get("https://example.com")
    ///     .with_header("hello", "world!")
    ///     .with_header("goodbye", "latency!");
    /// let names = req.get_header_names_str();
    /// assert_eq!(names.len(), 2);
    /// assert!(names.contains(&"hello"));
    /// assert!(names.contains(&"goodbye"));
    /// ```
    pub fn get_header_names_str(&self) -> Vec<&str> {
        self.get_header_names().map(|n| n.as_str()).collect()
    }

    /// Get an iterator of all the request's header names.
    ///
    /// # Examples
    ///
    /// You can turn the iterator into collection, like [`Vec`]:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// # use fastly::http::header::HeaderName;
    /// let req = Request::get("https://example.com")
    ///     .with_header("hello", "world!")
    ///     .with_header("goodbye", "latency!");
    ///
    /// let values: Vec<&HeaderName> = req.get_header_names().collect();
    /// assert_eq!(values.len(), 2);
    /// assert!(values.contains(&&HeaderName::from_static("hello")));
    /// assert!(values.contains(&&HeaderName::from_static("goodbye")));
    /// ```
    ///
    /// You can use the iterator in a loop:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::get("https://example.com")
    ///     .with_header("hello", "world!")
    ///     .with_header("goodbye", "latency!");
    ///
    /// for name in req.get_header_names() {
    ///     log::debug!("saw header: {:?}", name);
    /// }
    /// ```
    pub fn get_header_names(&self) -> impl Iterator<Item = &HeaderName> {
        self.headers.keys()
    }

    /// Set a request header to the given value, discarding any previous values for the given
    /// header name.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/header-name-value-argument.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::get("https://example.com");
    ///
    /// req.set_header("hello", "world!");
    /// assert_eq!(req.get_header_str("hello"), Some("world!"));
    ///
    /// req.set_header("hello", "universe!");
    ///
    /// let values = req.get_header_all_str("hello");
    /// assert_eq!(values.len(), 1);
    /// assert!(!values.contains(&"world!"));
    /// assert!(values.contains(&"universe!"));
    /// ```
    pub fn set_header(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue) {
        self.headers.insert(name.into_owned(), value.into_owned());
    }

    /// Add a request header with given value.
    ///
    /// Unlike [`set_header()`][`Self::set_header()`], this does not discard existing values for the
    /// same header name.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/header-name-value-argument.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::get("https://example.com");
    ///
    /// req.set_header("hello", "world!");
    /// assert_eq!(req.get_header_str("hello"), Some("world!"));
    ///
    /// req.append_header("hello", "universe!");
    ///
    /// let values = req.get_header_all_str("hello");
    /// assert_eq!(values.len(), 2);
    /// assert!(values.contains(&"world!"));
    /// assert!(values.contains(&"universe!"));
    /// ```
    pub fn append_header(&mut self, name: impl ToHeaderName, value: impl ToHeaderValue) {
        self.headers.append(name.into_owned(), value.into_owned());
    }

    /// Remove all request headers of the given name, and return one of the removed header values
    /// if any were present.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/removes-one-header.md")
    )]
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/header-name-argument.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// # use fastly::http::HeaderValue;
    /// let mut req = Request::get("https://example.com").with_header("hello", "world!");
    /// assert_eq!(req.get_header_str("hello"), Some("world!"));
    /// assert_eq!(req.remove_header("hello"), Some(HeaderValue::from_static("world!")));
    /// assert!(req.remove_header("not-present").is_none());
    /// ```
    pub fn remove_header(&mut self, name: impl ToHeaderName) -> Option<HeaderValue> {
        self.headers.remove(name.into_borrowable().as_ref())
    }

    /// Remove all request headers of the given name, and return one of the removed header values as
    /// a string if any were present.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/removes-one-header.md")
    )]
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/header-name-argument.md")
    )]
    ///
    /// # Panics
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/panics-reqresp-remove-header-utf8.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::get("https://example.com").with_header("hello", "world!");
    /// assert_eq!(req.get_header_str("hello"), Some("world!"));
    /// assert_eq!(req.remove_header_str("hello"), Some("world!".to_string()));
    /// assert!(req.remove_header_str("not-present").is_none());
    /// ```
    pub fn remove_header_str(&mut self, name: impl ToHeaderName) -> Option<String> {
        let name = name.into_borrowable();
        if let Some(hdr) = self.remove_header(name.as_ref()) {
            Some(
                hdr.to_str()
                    .map(|s| s.to_owned())
                    .unwrap_or_else(|_| panic!("non-UTF-8 HTTP header value for header: {}", name)),
            )
        } else {
            None
        }
    }

    /// Builder-style equivalent of [`set_method()`][`Self::set_method()`].
    pub fn with_method(mut self, method: impl ToMethod) -> Self {
        self.set_method(method);
        self
    }

    /// Get the request method as a string.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::get("https://example.com");
    /// assert_eq!(req.get_method_str(), "GET");
    pub fn get_method_str(&self) -> &str {
        self.get_method().as_str()
    }

    /// Get the request method.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// use fastly::http::Method;
    /// fn log_method(req: &Request) {
    ///     match req.get_method() {
    ///         &Method::GET | &Method::HEAD => log::debug!("method was a GET or HEAD"),
    ///         &Method::POST => log::debug!("method was a POST"),
    ///         _ => log::debug!("method was something else"),
    ///     }
    /// }
    pub fn get_method(&self) -> &Method {
        &self.method
    }

    /// Set the request method.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/method-argument.md")
    )]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// use fastly::http::Method;
    ///
    /// let mut req = Request::get("https://example.com");
    /// req.set_method(Method::POST);
    /// assert_eq!(req.get_method(), &Method::POST);
    /// ```
    pub fn set_method<'a>(&mut self, method: impl ToMethod) {
        self.method = method.into_owned();
    }

    /// Builder-style equivalent of [`set_url()`][`Self::set_url()`].
    pub fn with_url(mut self, url: impl ToUrl) -> Self {
        self.set_url(url);
        self
    }

    /// Get the request URL as a string.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::get("https://example.com");
    /// assert_eq!(req.get_url_str(), "https://example.com");
    /// ```
    pub fn get_url_str(&self) -> &str {
        self.get_url().as_str()
    }

    /// Get a shared reference to the request URL.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::get("https://example.com/hello#world");
    /// let url = req.get_url();
    /// assert_eq!(url.host_str(), Some("example.com"));
    /// assert_eq!(url.path(), "/hello");
    /// assert_eq!(url.fragment(), Some("world"));
    /// ```
    pub fn get_url(&self) -> &Url {
        &self.url
    }

    /// Get a mutable reference to the request URL.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::get("https://example.com/");
    ///
    /// let url = req.get_url_mut();
    /// url.set_path("/hello");
    /// url.set_fragment(Some("world"));
    ///
    /// assert_eq!(req.get_url_str(), "https://example.com/hello#world");
    /// ```
    pub fn get_url_mut(&mut self) -> &mut Url {
        &mut self.url
    }

    /// Set the request URL.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/url-argument.md")
    )]
    pub fn set_url(&mut self, url: impl ToUrl) {
        self.url = url.into_owned();
    }

    /// Get the path component of the request URL.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::get("https://example.com/hello#world");
    /// assert_eq!(req.get_path(), "/hello");
    /// ```
    pub fn get_path(&self) -> &str {
        self.get_url().path()
    }

    /// Builder-style equivalent of [`set_path()`][`Self::set_path()`].
    pub fn with_path(mut self, path: &str) -> Self {
        self.set_path(path);
        self
    }

    /// Set the path component of the request URL.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::get("https://example.com/");
    /// req.set_path("/hello");
    /// assert_eq!(req.get_url_str(), "https://example.com/hello");
    /// ```
    pub fn set_path(&mut self, path: &str) {
        self.get_url_mut().set_path(path);
    }

    /// Get the query component of the request URL, if it exists, as a percent-encoded ASCII string.
    ///
    /// This is a shorthand for `self.get_url().query()`; see [`Url::query()`] for details and other
    /// query manipulation functions.
    pub fn get_query_str(&self) -> Option<&str> {
        self.get_url().query()
    }

    /// Attempt to parse the query component of the request URL into the specified datatype.
    ///
    #[cfg_attr(
        feature = "unstable-doc",
        doc(include = "../../docs/snippets/returns-deserializeowned.md")
    )]
    ///
    /// # Errors
    ///
    /// This method returns [`serde_urlencoded::de::Error`] if deserialization fails.
    ///
    /// # Examples
    ///
    /// Parsing into a vector of string pairs:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let req = Request::get("https://example.com/foo?hello=%F0%9F%8C%90!&bar=baz");
    /// let pairs: Vec<(String, String)> = req.get_query().unwrap();
    /// assert_eq!((pairs[0].0.as_str(), pairs[0].1.as_str()), ("hello", "🌐!"));
    /// ```
    ///
    /// Parsing into a mapping between strings (note that duplicates are removed since
    /// [`HashMap`][`std::collections::HashMap`] is not a multimap):
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// use std::collections::HashMap;
    /// let req = Request::get("https://example.com/foo?hello=%F0%9F%8C%90!&bar=baz&bar=quux");
    /// let map: HashMap<String, String> = req.get_query().unwrap();
    /// assert_eq!(map.len(), 2);
    /// assert_eq!(map["hello"].as_str(), "🌐!");
    /// ```
    ///
    /// Parsing into a custom type that derives [`serde::de::Deserialize`]:
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// #[derive(serde::Deserialize)]
    /// struct MyData {
    ///     name: String,
    ///     count: u64,
    /// }
    /// let mut req = Request::get("https://example.com/?name=Computers&count=1024");
    /// let my_data = req.take_body_form::<MyData>().unwrap();
    /// assert_eq!(&my_data.name, "Computers");
    /// assert_eq!(my_data.count, 1024);
    /// ```
    pub fn get_query<T: DeserializeOwned>(&self) -> Result<T, serde_urlencoded::de::Error> {
        serde_urlencoded::from_str(self.url.query().unwrap_or(""))
    }

    /// Builder-style equivalent of [`set_query_str()`][`Self::set_query_str()`].
    pub fn with_query_str(mut self, query: impl AsRef<str>) -> Self {
        self.set_query_str(query);
        self
    }

    /// Set the query string of the request URL query component to the given string, performing
    /// percent-encoding if necessary.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::get("https://example.com/foo");
    /// req.set_query_str("hello=🌐!&bar=baz");
    /// assert_eq!(req.get_url_str(), "https://example.com/foo?hello=%F0%9F%8C%90!&bar=baz");
    /// ```
    pub fn set_query_str(&mut self, query: impl AsRef<str>) {
        self.get_url_mut().set_query(Some(query.as_ref()))
    }

    /// Builder-style equivalent of [`set_query()`][`Self::set_query()`].
    pub fn with_query(
        mut self,
        query: &impl Serialize,
    ) -> Result<Self, serde_urlencoded::ser::Error> {
        self.set_query(query)?;
        Ok(self)
    }

    /// Convert the given value to `application/x-www-form-urlencoded` format and set that data as
    /// the request URL query component.
    ///
    /// The given value must implement [`serde::Serialize`]; see the trait documentation for
    /// details.
    ///
    /// # Errors
    ///
    /// This method returns [`serde_urlencoded::ser::Error`] if serialization fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// #[derive(serde::Serialize)]
    /// struct MyData {
    ///     name: String,
    ///     count: u64,
    /// }
    /// let my_data = MyData { name: "Computers".to_string(), count: 1024 };
    /// let mut req = Request::get("https://example.com/foo");
    /// req.set_query(&my_data).unwrap();
    /// assert_eq!(req.get_url_str(), "https://example.com/foo?name=Computers&count=1024");
    /// ```
    pub fn set_query(
        &mut self,
        query: &impl Serialize,
    ) -> Result<(), serde_urlencoded::ser::Error> {
        let s = serde_urlencoded::to_string(query)?;
        self.get_url_mut().set_query(Some(&s));
        Ok(())
    }

    /// Remove the query component from the request URL, if one exists.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// let mut req = Request::get("https://example.com/foo?hello=%F0%9F%8C%90!&bar=baz");
    /// req.remove_query();
    /// assert_eq!(req.get_url_str(), "https://example.com/foo");
    /// ```
    pub fn remove_query(&mut self) {
        self.get_url_mut().set_query(None);
    }

    /// Builder-style equivalent of [`set_version()`][`Self::set_version()`].
    pub fn with_version(mut self, version: Version) -> Self {
        self.set_version(version);
        self
    }

    /// Get the HTTP version of this request.
    pub fn get_version(&self) -> Version {
        self.version
    }

    /// Set the HTTP version of this request.
    pub fn set_version(&mut self, version: Version) {
        self.version = version;
    }

    /// Builder-style equivalent of [`set_pass()`][`Self::set_pass()`].
    pub fn with_pass(mut self, pass: bool) -> Self {
        self.set_pass(pass);
        self
    }

    /// Set whether this request should be cached if sent to a backend.
    ///
    /// By default this is `false`, which means the backend will only be reached if a cached
    /// response is not available. Set this to `true` to send the request directly to the backend
    /// without caching.
    ///
    /// # Overrides
    ///
    /// Setting this to `true` overrides any other custom caching behaviors for this request, such
    /// as [`Request::set_ttl()`] or [`Request::set_surrogate_key()`].
    pub fn set_pass(&mut self, pass: bool) {
        self.cache_override.set_pass(pass);
    }

    /// Builder-style equivalent of [`set_ttl()`][`Self::set_ttl()`].
    pub fn with_ttl(mut self, ttl: u32) -> Self {
        self.set_ttl(ttl);
        self
    }

    /// Override the caching behavior of this request to use the given Time to Live (TTL), in seconds.
    ///
    /// # Overrides
    ///
    /// This overrides the behavior specified in the response headers, and sets the
    /// [`pass`][`Self::set_pass()`] behavior to `false`.
    pub fn set_ttl(&mut self, ttl: u32) {
        self.cache_override.set_ttl(ttl);
    }

    /// Builder-style equivalent of [`set_stale_while_revalidate()`][`Self::set_stale_while_revalidate()`].
    pub fn with_stale_while_revalidate(mut self, swr: u32) -> Self {
        self.set_stale_while_revalidate(swr);
        self
    }

    /// Override the caching behavior of this request to use the given `stale-while-revalidate`
    /// time, in seconds.
    ///
    /// # Overrides
    ///
    /// This overrides the behavior specified in the response headers, and sets the
    /// [`pass`][`Self::set_pass()`] behavior to `false`.
    pub fn set_stale_while_revalidate(&mut self, swr: u32) {
        self.cache_override.set_stale_while_revalidate(swr);
    }

    /// Builder-style equivalent of [`set_pci()`][`Self::set_pci()`].
    pub fn with_pci(mut self, pci: bool) -> Self {
        self.set_pci(pci);
        self
    }

    /// Override the caching behavior of this request to enable or disable PCI/HIPAA-compliant non-volatile caching.
    ///
    /// By default, this is `false`, which means the request may not be PCI/HIPAA-compliant. Set it
    /// to `true` to enable compliant caching.
    ///
    /// See the [Fastly PCI-Compliant Caching and Delivery
    /// documentation](https://docs.fastly.com/products/pci-compliant-caching-and-delivery) for
    /// details.
    ///
    /// # Overrides
    ///
    /// This sets the [`pass`][`Self::set_pass()`] behavior to `false`.
    pub fn set_pci(&mut self, pci: bool) {
        self.cache_override.set_pci(pci);
    }

    /// Builder-style equivalent of [`set_surrogate_key()`][`Self::set_surrogate_key()`].
    pub fn with_surrogate_key(mut self, sk: HeaderValue) -> Self {
        self.set_surrogate_key(sk);
        self
    }

    /// Override the caching behavior of this request to include the given surrogate key, provided
    /// as a header value.
    ///
    /// See the [Fastly surrogate keys
    /// guide](https://docs.fastly.com/en/guides/purging-api-cache-with-surrogate-keys) for details.
    ///
    /// # Overrides
    ///
    /// This sets the [`pass`][`Self::set_pass()`] behavior to `false`, and extends (but does not
    /// replace) any `Surrogate-Key` response headers from the backend.
    pub fn set_surrogate_key(&mut self, sk: HeaderValue) {
        self.cache_override.set_surrogate_key(sk);
    }

    /// Returns the IP address of the client making the HTTP request.
    ///
    /// Returns `None` if this is not the client request.
    pub fn get_client_ip_addr(&self) -> Option<IpAddr> {
        if !self.is_from_client() {
            return None;
        }
        self::handle::client_ip_addr()
    }

    /// Returns the client request's header names exactly as they were originally received.
    ///
    /// This includes both the original character cases, as well as the original order of the
    /// received headers.
    ///
    /// Returns `None` if this is not the client request.
    pub fn get_original_header_names(&self) -> Option<impl Iterator<Item = String>> {
        if !self.is_from_client() {
            return None;
        } else {
            Some(
                self::handle::client_original_header_names_impl(
                    limits::INITIAL_HEADER_NAME_BUF_SIZE,
                    RequestLimits::get_max_header_name_bytes(),
                )
                .map(|res| res.expect("original request header name too large")),
            )
        }
    }

    /// Returns the number of headers in the client request as originally received.
    ///
    /// Returns `None` if this is not the client request.
    pub fn get_original_header_count(&self) -> Option<u32> {
        if !self.is_from_client() {
            return None;
        }
        Some(self::handle::client_original_header_count())
    }

    /// Get the raw bytes sent by the client in the TLS ClientHello message.
    ///
    /// See [RFC 5246](https://tools.ietf.org/html/rfc5246#section-7.4.1.2) for details.
    ///
    /// Returns `None` if this is not the client request.
    pub fn get_tls_client_hello(&self) -> Option<&[u8]> {
        if !self.is_from_client() {
            return None;
        }

        self::handle::client_tls_client_hello()
    }

    /// Get the cipher suite used to secure the client TLS connection.
    ///
    /// The value returned will be consistent with the [OpenSSL
    /// name](https://testssl.sh/openssl-iana.mapping.html) for the cipher suite.
    ///
    /// Returns `None` if this is not the client request.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// assert_eq!(Request::from_client().get_tls_cipher_openssl_name().unwrap(), "ECDHE-RSA-AES128-GCM-SHA256");
    /// ```
    pub fn get_tls_cipher_openssl_name(&self) -> Option<&'static str> {
        if !self.is_from_client() {
            return None;
        }

        self::handle::client_tls_cipher_openssl_name()
    }

    /// Get the TLS protocol version used to secure the client TLS connection.
    ///
    /// Returns `None` if this is not the client request.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use fastly::Request;
    /// assert_eq!(Request::from_client().get_tls_protocol().unwrap(), "TLSv1.2");
    /// ```
    pub fn get_tls_protocol(&self) -> Option<&'static str> {
        if !self.is_from_client() {
            return None;
        }
        self::handle::client_tls_protocol()
    }

    /// Create a [`Request`] from the low-level [`handle` API][`crate::handle`].
    ///
    /// # Errors
    ///
    /// This conversion can fail if the request exceeds the limits specified by [`RequestLimits`].
    pub fn from_handles(
        req_handle: RequestHandle,
        body_handle: Option<BodyHandle>,
    ) -> Result<Self, BufferSizeError> {
        let req_limits = limits::REQUEST_LIMITS.read().unwrap();
        let method = req_handle
            .get_method_impl(limits::INITIAL_METHOD_BUF_SIZE, req_limits.max_method_bytes)?;
        let url =
            req_handle.get_url_impl(limits::INITIAL_URL_BUF_SIZE, req_limits.max_url_bytes)?;

        let mut req = Request::new(method, url).with_version(req_handle.get_version());
        req.is_from_client = true;

        for name in req_handle.get_header_names_impl(
            limits::INITIAL_HEADER_NAME_BUF_SIZE,
            req_limits.max_header_name_bytes,
        ) {
            let name = name?;
            for value in req_handle.get_header_values_impl(
                &name,
                limits::INITIAL_HEADER_VALUE_BUF_SIZE,
                req_limits.max_header_value_bytes,
            ) {
                let value = value?;
                req.append_header(&name, value);
            }
        }

        if let Some(body) = body_handle {
            req.set_body(body);
        }
        Ok(req)
    }

    /// Convert a [`Request`] into the low-level [`handle` API][`crate::handle`].
    pub fn into_handles(mut self) -> (RequestHandle, Option<BodyHandle>) {
        self.to_handles()
    }

    /// Make handles from a `Request`.
    ///
    /// Note that this is private in order to maintain the right ownership model in the public API.
    fn to_handles(&mut self) -> (RequestHandle, Option<BodyHandle>) {
        let req_handle = {
            let mut req_handle = RequestHandle::new();
            // Set the handle's version, method, URI, and cache override using the request.
            req_handle.set_version(self.version);
            req_handle.set_method(&self.method);
            req_handle.set_url(&self.url);
            req_handle.set_cache_override(&self.cache_override);
            for name in self.headers.keys() {
                // Copy the request's header values to the handle.
                req_handle.set_header_values(name, self.headers.get_all(name));
            }
            req_handle
        };
        let body_handle = if let Some(body) = self.try_take_body() {
            Some(body.into_handle())
        } else {
            None
        };
        (req_handle, body_handle)
    }
}

/// Anything that we need to make a full roundtrip through the `http` types that doesn't have a more
/// concrete corresponding type.
#[derive(Debug)]
struct FastlyExts {
    cache_override: CacheOverride,
    is_from_client: bool,
}

impl Into<http::Request<Body>> for Request {
    fn into(self) -> http::Request<Body> {
        let mut req = http::Request::new(self.body.unwrap_or_else(|| Body::new()));
        req.extensions_mut().insert(FastlyExts {
            cache_override: self.cache_override,
            is_from_client: self.is_from_client,
        });
        *req.headers_mut() = self.headers;
        *req.method_mut() = self.method;
        *req.uri_mut() = self
            .url
            .into_string()
            .parse()
            .expect("Url to Uri conversion shouldn't fail, but did");
        *req.version_mut() = self.version;
        req
    }
}

impl From<http::Request<Body>> for Request {
    fn from(from: http::Request<Body>) -> Self {
        let (mut parts, body) = from.into_parts();
        let (cache_override, is_from_client) = parts
            .extensions
            .remove()
            .map(|exts: FastlyExts| (exts.cache_override, exts.is_from_client))
            .unwrap_or_else(|| (CacheOverride::default(), false));
        Request {
            version: parts.version,
            method: parts.method,
            url: Url::parse(&parts.uri.to_string())
                .expect("Uri to Url conversion shouldn't fail, but did"),
            headers: parts.headers,
            body: Some(body),
            cache_override,
            is_from_client,
        }
    }
}

/// The reason that a request sent to a backend failed.
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum SendErrorCause {
    /// The backend responded with something that was not valid HTTP.
    Invalid,
    /// The backend responded, but we didn't get a complete response before the connection closed.
    Incomplete,
    /// Ran out of buffer space for part of the response.
    ///
    /// See the [`limits`][crate::limits] module to adjust the maximum buffer sizes.
    BufferSize(BufferSizeError),
    /// All other errors.
    Generic(Error),
}

impl fmt::Display for SendErrorCause {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            SendErrorCause::Invalid => {
                write!(f, "response was invalid HTTP")
            }
            SendErrorCause::Incomplete => {
                write!(f, "response was not a complete HTTP message")
            }
            SendErrorCause::BufferSize(buffer_size_error) => {
                write!(f, "response included a {} that exceeded a provided buffer's capacity (needed {} bytes)", buffer_size_error.buffer_kind, buffer_size_error.needed_buf_size)
            }
            SendErrorCause::Generic(e) => {
                write!(f, "generic send error: {}", e)
            }
        }
    }
}

impl SendErrorCause {
    pub(crate) fn status(cause: fastly_shared::FastlyStatus) -> Self {
        match cause {
            fastly_shared::FastlyStatus::HTTPINVALID => SendErrorCause::Invalid,
            fastly_shared::FastlyStatus::HTTPINCOMPLETE => SendErrorCause::Incomplete,
            other => SendErrorCause::Generic(Error::msg(format!(
                "SendError with unknown FastlyStatus code: {}",
                other.code
            ))),
        }
    }
}

/// An error that occurred while sending a request.
///
/// While the body of a request is always consumed when sent, you can recover the headers and other
/// request metadata of the request that failed using `SendError::into_sent_req()`.
///
/// use [`SendError::root_cause()`] to inspect details about what caused the error.
#[derive(Debug, Error)]
#[error("error sending request: {error} to backend {backend}")]
pub struct SendError {
    backend: String,
    sent_req: Request,
    #[source]
    error: SendErrorCause,
}

impl SendError {
    fn new(backend: impl Into<String>, sent_req: Request, error: SendErrorCause) -> Self {
        SendError {
            backend: backend.into(),
            sent_req,
            error: error.into(),
        }
    }

    /// Create a `SendError` from a `FastlyResponseMetadata` and an underlying error.
    ///
    /// Panics if the metadata does not contain a backend and a sent request. This should only be
    /// called in contexts where those are guaranteed to be present, like the metadata from a
    /// `PendingRequest`.
    pub(crate) fn from_resp_metadata(
        mut metadata: FastlyResponseMetadata,
        error: SendErrorCause,
    ) -> Self {
        let sent_req = metadata.take_sent_req().expect("sent_req must be present");
        let backend_name = metadata.backend().expect("backend must be present").name();
        Self::new(backend_name, sent_req, error)
    }

    /// Create a `SendError` from a `PendingRequest` and an underlying error.
    fn from_pending_req(pending_req: PendingRequest, error: SendErrorCause) -> Self {
        Self::from_resp_metadata(pending_req.metadata, error)
    }

    /// Get the name of the backend that returned this error.
    pub fn backend_name(&self) -> &str {
        self.backend.as_str()
    }

    /// Get the underlying cause of this `SendError`.
    ///
    /// This is the same cause that would be returned by `err.source().downcast_ref::<SendErrorCause>()`, but more direct.
    pub fn root_cause(&self) -> &SendErrorCause {
        &self.error
    }

    /// Convert the error back into the request that was originally sent.
    ///
    /// Since the original request's body is consumed by sending it, the body in the returned
    /// request is empty. To add a new body to the request, use [`Request::with_body()`], for example:
    ///
    /// ```no_run
    /// # use fastly::{Body, Error, Request};
    /// # fn f(bereq: Request) -> Result<(), Error> {
    /// if let Err(e) = bereq.send("my_backend") {
    ///     let new_body = Body::from("something new");
    ///     let new_req = e.into_sent_req().with_body(new_body);
    ///     new_req.send("my_other_backend")?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn into_sent_req(self) -> Request {
        self.sent_req
    }
}

/// Check whether a request looks suitable for sending to a backend.
///
/// Note that this is *not* meant to be a filter for things that could cause security issues, it is
/// only meant to catch errors before the hostcalls do in order to yield friendlier error messages.
fn validate_request(req: &Request) -> Result<(), Error> {
    let scheme_ok = req.url.scheme().eq_ignore_ascii_case("http")
        || req.url.scheme().eq_ignore_ascii_case("https");
    ensure!(
        scheme_ok && req.url.has_authority(),
        "request URIs must have a scheme (http/https) and an authority (host)"
    );
    Ok(())
}

/// Additional Fastly-specific metadata for requests.
#[derive(Debug)]
pub(crate) struct FastlyRequestMetadata {
    backend: Option<Backend>,
    cache_override: CacheOverride,
}