HTTP/1.1¶
palfrey.protocols.http
¶
HTTP/1.1 request parsing and response encoding with multiple backend support.
This module implements HTTP/1.1 protocol handling including request parsing via httptools (C-based, preferred) or h11 (pure Python fallback), ASGI scope construction, request body streaming, and response encoding with keep-alive decision logic. The module provides building blocks for keep-alive detection, 100-continue handling, chunked transfer encoding, and content-length calculations required for standards-compliant HTTP/1.1 message framing.
Key Design Decisions: - Dual-backend parser selection: httptools by default (fast C library) falls back to h11 for compatibility or when C extensions are unavailable. - Request/Response dataclasses normalize heterogeneous wire formats into consistent, Python-friendly structures (bytes for headers, chunks for body). - Keep-alive is determined by HTTP version and Connection header, not by response body completion—allowing pipelined requests to be queued immediately. - 100-continue handling is async-callback-driven for proper backpressure integration.
Key Functions
- build_http_scope: Constructs ASGI scope dict from HTTPRequest and metadata.
- run_http_asgi: Main coroutine cycling through request/response pairs.
- encode_http_response: Serializes HTTPResponse to wire bytes with chunking.
- read_http_request: Parses wire bytes into HTTPRequest dataclass.
- should_keep_alive: Determines if connection should remain open after response.
HTTPBodyStream
dataclass
¶
Deferred reader for a fixed-size HTTP request body.
The server uses this when an application may respond before consuming the body. It keeps the public read_http_request() behavior buffered by default while allowing the connection loop to preserve request framing.
Source code in palfrey/protocols/http.py
receive()
async
¶
Read the next request-body chunk and report whether more data remains.
Source code in palfrey/protocols/http.py
drain()
async
¶
HTTPRequest
dataclass
¶
Data container for a parsed HTTP request, including headers and body content.
This class normalizes the body representation into both a contiguous byte string and a list of chunks, facilitating easier processing for both synchronous logic and asynchronous streaming.
| ATTRIBUTE | DESCRIPTION |
|---|---|
method |
The HTTP method (e.g., 'GET', 'POST').
TYPE:
|
target |
The full request URI or path.
TYPE:
|
http_version |
The protocol version (e.g., 'HTTP/1.1').
TYPE:
|
headers |
Header pairs.
TYPE:
|
body |
The complete request body as a single byte string.
TYPE:
|
body_chunks |
The body split into chunks, as received from the wire.
TYPE:
|
Source code in palfrey/protocols/http.py
__post_init__()
¶
Synchronizes the body and body_chunks attributes after initialization.
Ensures that if body_chunks is provided, the body attribute reflects the concatenated content. If only body is provided, body_chunks is populated with a single-element list containing that body.
Source code in palfrey/protocols/http.py
HTTPResponse
dataclass
¶
Representation of an outgoing HTTP response constructed from ASGI events.
This object acts as a collector for headers and body chunks sent by the application before they are serialized to the network socket.
| ATTRIBUTE | DESCRIPTION |
|---|---|
status |
HTTP status code (default 500).
TYPE:
|
headers |
List of header tuples in bytes.
TYPE:
|
body_chunks |
Fragments of the response body.
TYPE:
|
chunked_encoding |
Whether the response uses Transfer-Encoding: chunked.
TYPE:
|
suppress_body |
If True, the body is omitted (e.g., for HEAD requests).
TYPE:
|
Source code in palfrey/protocols/http.py
HTTPResponseStartedError
¶
Bases: RuntimeError
Raised when an ASGI error occurs after response start.
Source code in palfrey/protocols/http.py
read_http_request(reader, *, max_head_size=1048576, body_limit=4194304, parser_mode='auto', stream_body=False)
async
¶
Reads and parses a full HTTP request (head and body) from the reader.
| PARAMETER | DESCRIPTION |
|---|---|
reader
|
The client stream reader.
TYPE:
|
max_head_size
|
Max allowed bytes for the request line and headers.
TYPE:
|
body_limit
|
Max allowed bytes for the body.
TYPE:
|
parser_mode
|
Choice of parser ('httptools', 'h11', or 'auto').
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
HTTPRequest | None
|
HTTPRequest | None: The parsed request, or None if the client disconnected. |
Source code in palfrey/protocols/http.py
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 | |
build_http_scope(request, *, client, server, root_path, is_tls, app_state=None, asgi_version='3.0')
¶
Converts an internal HTTPRequest into an ASGI 3.0 scope dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
Parsed request data.
TYPE:
|
client
|
IP and port of the client.
TYPE:
|
server
|
IP and port of the server.
TYPE:
|
root_path
|
The mounting point of the application.
TYPE:
|
is_tls
|
True if connection is encrypted.
TYPE:
|
app_state
|
Lifespan state to shallow-copy into the per-request scope.
TYPE:
|
asgi_version
|
ASGI callable version reported in the scope.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Scope
|
A dictionary conforming to the ASGI HTTP specification.
TYPE:
|
Source code in palfrey/protocols/http.py
run_http_asgi(app, scope, request_body, *, expect_100_continue=False, on_100_continue=None, on_response_start=None, on_response_body=None)
async
¶
Orchestrates the ASGI request/response lifecycle with high-performance formatting.
This function manages the strict state machine required by the ASGI HTTP specification. It incorporates several critical performance optimizations:
- Single-Chunk Optimization: Defers finalizing headers until the first body chunk arrives.
If the app yields a single chunk (
more_body=False) without aContent-Length, it calculates it instantly to avoid the overhead of HTTP chunked transfer framing. - In-Flight Chunk Framing: If
Transfer-Encoding: chunkedis actually required, it formats the hex framing continuously during the app'ssend()loop rather than post-processing.
| PARAMETER | DESCRIPTION |
|---|---|
app
|
The user-provided ASGI application callable.
TYPE:
|
scope
|
The ASGI connection scope dictionary.
TYPE:
|
request_body
|
The pre-buffered input body chunks.
TYPE:
|
expect_100_continue
|
If the client expects a 100-Continue response.
TYPE:
|
on_100_continue
|
Callback to trigger the 100 status code transmission.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
HTTPResponse
|
The resulting parsed response state ready for wire encoding.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If the ASGI application violates the protocol sequence or crashes. |
Source code in palfrey/protocols/http.py
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 | |
append_default_response_headers(response, config, *, default_headers=None)
¶
Applies configured default headers to the response.
Injects headers like 'Server' and 'Date' if enabled and not already present.
| PARAMETER | DESCRIPTION |
|---|---|
response
|
The response object to update.
TYPE:
|
config
|
Application configuration.
TYPE:
|
default_headers
|
Cached list of headers for fast-path insertion.
TYPE:
|
Source code in palfrey/protocols/http.py
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 | |
encode_http_response_head(response, keep_alive)
¶
Serializes the HTTP response status line and headers.
Handles status line and headers while preserving chunked transfer metadata for callers that stream body chunks separately.
| PARAMETER | DESCRIPTION |
|---|---|
response
|
The response to serialize.
TYPE:
|
keep_alive
|
Whether the connection should be kept alive.
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
bytes
|
Serialized status and header fragments.
TYPE::
|
Source code in palfrey/protocols/http.py
encode_http_response_body_chunk(response, body, *, more_body)
¶
Serializes a single ASGI response body event into wire bytes.
Source code in palfrey/protocols/http.py
encode_http_response_head_and_body_chunk(response, body, *, keep_alive, more_body)
¶
Serialize response headers and the first body event in one pass.
Source code in palfrey/protocols/http.py
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 | |
encode_http_response_chunks(response, keep_alive)
¶
Serializes the HTTPResponse into a sequence of bytes chunks.
Handles status line, headers, and body encoding including chunked transfer.
| PARAMETER | DESCRIPTION |
|---|---|
response
|
The response to serialize.
TYPE:
|
keep_alive
|
Whether the connection should be kept alive.
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
bytes
|
Serialized fragments of the HTTP response.
TYPE::
|
Source code in palfrey/protocols/http.py
encode_http_response(response, keep_alive)
¶
Zero-copy serialization of the HTTPResponse into raw wire bytes.
This function is aggressively optimized to avoid intermediate string formatting
and memory allocations. It appends pre-encoded bytes into a flat list and performs
a single C-level b"".join().
| PARAMETER | DESCRIPTION |
|---|---|
response
|
The finalized response data collected from the app.
TYPE:
|
keep_alive
|
Indicates if the connection will remain open.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bytes
|
The fully serialized HTTP response ready for
TYPE:
|
Source code in palfrey/protocols/http.py
should_keep_alive(request, response)
¶
Determines if the TCP connection should persist based on headers and protocol version.
Handles the nuances between HTTP/1.0 explicit keep-alive and HTTP/1.1 explicit close.
| PARAMETER | DESCRIPTION |
|---|---|
request
|
The parsed incoming request.
TYPE:
|
response
|
The finalized outgoing response.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if the connection should be kept alive, False to close.
TYPE:
|
Source code in palfrey/protocols/http.py
is_websocket_upgrade(request)
¶
Checks if the request is initiating a WebSocket handshake.
Source code in palfrey/protocols/http.py
requires_100_continue(request)
¶
Verifies if the client is waiting for a '100 Continue' response before sending the body.