CodeSampleX

Ejemplo

h11 0.16.0: HTTP/1.1 client request and server response parsing with h11 Connection state machine

Muestra verificada para pypi h11 0.16.0: HTTP/1.1 client request and server response parsing with h11 Connection state machine. El contrato se ejecutó en…

sha256:df3b87a39dbbc0edc1645ae90188d7e1ddf19148633431876501090d505ee820

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-28

Caso

HOW
Objetivo
HTTP/1.1 client request and server response parsing with h11 Connection state machine
Paquetes
Símbolos
  • h11.Connection
  • h11.Data
  • h11.EndOfMessage
  • h11.Request
  • h11.Response
Entorno
python
Creado
2026-08-28T03:43:30Z

Contrato

  1. Connection(our_role=CLIENT) and Connection(our_role=SERVER) initialize the connection with matching our_role, their_role, and initial IDLE states.
  2. Request generates valid HTTP/1.1 request wire bytes when sent by a client Connection, and receive_data() on server Connection parses it into a Request event.
  3. Data encodes and delivers payload bytes between client and server Connections.
  4. EndOfMessage signals completion of a request stream and server next_event() yields NEED_DATA when receive buffer is empty.
  5. Response generates HTTP/1.1 response wire bytes when sent by a server Connection, and receive_data() on client Connection parses it into Response, Data, and EndOfMessage events.
  6. Receiving empty bytes with receive_data(b"") signals socket EOF and produces a ConnectionClosed event.
  7. Attempting invalid protocol operations, such as sending a Response from a CLIENT role Connection, raises LocalProtocolError.

Archivos

  • NOTES.md
  • PROMPT.md
  • csx.json
  • requirements.txt
  • spec.json
  • test/contract.py

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# h11 HTTP/1.1 Connection state machine sample

This sample pins `h11` 0.16.0 and verifies core HTTP/1.1 protocol state machine operations using `Connection`, `Request`, `Response`, `Data`, and `EndOfMessage`.

The contract verifies:
- `Connection` initializes roles (`CLIENT` and `SERVER`) with matching role attributes and initial `IDLE` state.
- `Request` event generation on client, wire serialization, and server-side parsing.
- `Data` event framing and transmission for HTTP request/response payloads.
- `EndOfMessage` signaling of stream termination and transition of server `next_event()` to `NEED_DATA`.
- `Response` generation on server, wire serialization, and client-side parsing of status, headers, and body.
- Receiving empty bytes `receive_data(b"")` indicates transport EOF and yields `ConnectionClosed`.
- Rejection of invalid state transitions (e.g. client sending `Response`) raising `LocalProtocolError`.
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: HTTP/1.1 client request and server response parsing with h11 Connection state machine
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/h11@0.16.0
Demonstrate these symbols/APIs:
  - h11.Connection
  - h11.Data
  - h11.EndOfMessage
  - h11.Request
  - h11.Response

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:ca4ed8702cfa0bffdde6d57476ce8622145e52f118fead4148a1822d44545178","contract":["Connection(our_role=CLIENT) and Connection(our_role=SERVER) initialize the connection with matching our_role, their_role, and initial IDLE states.","Request generates valid HTTP/1.1 request wire bytes when sent by a client Connection, and receive_data() on server Connection parses it into a Request event.","Data encodes and delivers payload bytes between client and server Connections.","EndOfMessage signals completion of a request stream and server next_event() yields NEED_DATA when receive buffer is empty.","Response generates HTTP/1.1 response wire bytes when sent by a server Connection, and receive_data() on client Connection parses it into Response, Data, and EndOfMessage events.","Receiving empty bytes with receive_data(b\"\") signals socket EOF and produces a ConnectionClosed event.","Attempting invalid protocol operations, such as sending a Response from a CLIENT role Connection, raises LocalProtocolError."],"goal":"HTTP/1.1 client request and server response parsing with h11 Connection state machine","kind":"HOW","packages":["pkg:pypi/h11@0.16.0"],"schemaVersion":1,"symbols":["h11.Connection","h11.Data","h11.EndOfMessage","h11.Request","h11.Response"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","executionContext":"python","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/h11@0.16.0"],"schemaVersion":1,"subject":"pkg:pypi/h11@0.16.0","symbols":["h11.Connection","h11.Data","h11.EndOfMessage","h11.Request","h11.Response"],"verifierAdapter":"python@1"}
requirements.txt
h11==0.16.0
spec.json
{
  "schemaVersion": 1,
  "goal": "HTTP/1.1 client request and server response parsing with h11 Connection state machine",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/h11@0.16.0"
  ],
  "symbols": [
    "h11.Connection",
    "h11.Data",
    "h11.EndOfMessage",
    "h11.Request",
    "h11.Response"
  ]
}
test/contract.py
import h11
from h11 import (
    Connection,
    Request,
    Response,
    Data,
    EndOfMessage,
    ConnectionClosed,
    CLIENT,
    SERVER,
    NEED_DATA,
    PAUSED,
    IDLE,
    SEND_RESPONSE,
    DONE,
    LocalProtocolError,
)

# 1. Verify Connection initialization and role configuration for CLIENT and SERVER
client = Connection(our_role=CLIENT)
server = Connection(our_role=SERVER)

assert client.our_role == CLIENT
assert client.their_role == SERVER
assert server.our_role == SERVER
assert server.their_role == CLIENT
assert client.our_state == IDLE
assert client.their_state == IDLE
assert server.our_state == IDLE
assert server.their_state == IDLE

# 2. Verify Request creation, client-side serialization, and server-side parsing
req = Request(
    method="POST",
    target="/submit",
    headers=[
        ("Host", "example.com"),
        ("Content-Type", "application/json"),
        ("Content-Length", "18"),
    ],
)
assert req.method == b"POST"
assert req.target == b"/submit"

req_wire = client.send(req)
assert isinstance(req_wire, bytes)
assert b"POST /submit HTTP/1.1\r\n" in req_wire
assert b"host: example.com\r\n" in req_wire.lower()

server.receive_data(req_wire)
parsed_req = server.next_event()
assert isinstance(parsed_req, Request)
assert parsed_req.method == b"POST"
assert parsed_req.target == b"/submit"
assert parsed_req.http_version == b"1.1"
assert any(name.lower() == b"content-type" and value == b"application/json" for name, value in parsed_req.headers)

# 3. Verify Data event payload serialization, transmission, and deserialization
payload = b'{"status": "test"}'
client_data_event = Data(data=payload)
data_wire = client.send(client_data_event)
assert data_wire == payload

server.receive_data(data_wire)
parsed_data = server.next_event()
assert isinstance(parsed_data, Data)
assert parsed_data.data == payload

# 4. Verify EndOfMessage event indicates completion of request stream
client_eom_event = EndOfMessage()
eom_wire = client.send(client_eom_event)
assert eom_wire == b""

# With Content-Length satisfied, server yields EndOfMessage
parsed_eom = server.next_event()
assert isinstance(parsed_eom, EndOfMessage)
assert server.their_state == DONE
assert server.our_state == SEND_RESPONSE
assert server.next_event() is NEED_DATA

# 5. Verify Response generation by server and reception/parsing by client
resp = Response(
    status_code=200,
    headers=[
        ("Content-Type", "text/plain"),
        ("Content-Length", "5"),
        ("Connection", "close"),
    ],
)
resp_wire = server.send(resp)
resp_body_wire = server.send(Data(data=b"pong!"))
resp_eom_wire = server.send(EndOfMessage())

assert b"HTTP/1.1 200 " in resp_wire

client.receive_data(resp_wire + resp_body_wire + resp_eom_wire)
client_parsed_resp = client.next_event()
assert isinstance(client_parsed_resp, Response)
assert client_parsed_resp.status_code == 200
assert client_parsed_resp.http_version == b"1.1"

client_parsed_body = client.next_event()
assert isinstance(client_parsed_body, Data)
assert client_parsed_body.data == b"pong!"

client_parsed_eom = client.next_event()
assert isinstance(client_parsed_eom, EndOfMessage)
assert client.their_state == DONE or client.their_state == h11.MUST_CLOSE

# 6. Verify empty byte reception signals connection EOF (ConnectionClosed)
client.receive_data(b"")
eof_event = client.next_event()
assert isinstance(eof_event, ConnectionClosed)

# 7. Verify state machine violations raise LocalProtocolError
invalid_client = Connection(our_role=CLIENT)
try:
    invalid_client.send(Response(status_code=200, headers=[]))
    raise AssertionError("Expected LocalProtocolError when client attempts to send Response")
except LocalProtocolError:
    pass

print("CONTRACT PASS: h11 Connection, Request, Response, Data, EndOfMessage verified offline")

Seeder de origen

anónimo