HTTP Transport¶
HTTP transport using Falcon (server) and httpx2 (client). Requires pip install vgi-rpc[http].
Quick Start¶
Server¶
Create a WSGI app and serve it with any WSGI server (waitress, gunicorn, etc.):
from vgi_rpc import RpcServer, make_wsgi_app
server = RpcServer(MyService, MyServiceImpl())
app = make_wsgi_app(server)
# serve `app` with waitress, gunicorn, etc.
Client¶
from vgi_rpc import http_connect
with http_connect(MyService, "http://localhost:8080") as proxy:
result = proxy.echo(message="hello") # proxy is typed as MyService
Testing (no real server)¶
make_sync_client wraps a Falcon TestClient so you can test the full HTTP stack in-process:
from vgi_rpc import RpcServer
from vgi_rpc.http import http_connect, make_sync_client
server = RpcServer(MyService, MyServiceImpl())
client = make_sync_client(server)
with http_connect(MyService, client=client) as proxy:
assert proxy.echo(message="hello") == "hello"
Landing Page¶
By default, GET {prefix} (e.g. GET /vgi) returns an HTML landing page showing the vgi-rpc logo, the protocol name, server ID, and links. When the server has enable_describe=True, the landing page includes a link to the describe page.
To disable the landing page:
POST {prefix} returns 405 Method Not Allowed — it does not interfere with RPC routing.
Describe Page¶
When the server has enable_describe=True, GET {prefix}/describe (e.g. GET /vgi/describe) returns an HTML page listing all methods, their parameters (name, type, default), return types, docstrings, and method type badges (UNARY / STREAM). The __describe__ introspection method is filtered out.
Both enable_describe=True on the RpcServer and enable_describe_page=True (the default) on make_wsgi_app() are required.
To disable only the HTML page while keeping the __describe__ RPC method available:
Reserved path
When the describe page is active, the path {prefix}/describe is reserved for the HTML page. If your service has an RPC method literally named describe, you must set enable_describe_page=False.
Not-Found Page¶
By default, make_wsgi_app() installs a friendly HTML 404 page for any request that does not match an RPC route. If someone navigates to the server root or a random path in a browser, they see the vgi-rpc logo, the service protocol name, and a link to vgi-rpc.query.farm instead of a generic error.
This does not affect RPC clients — a request to a valid RPC route for a non-existent method still returns a machine-readable Arrow IPC error with HTTP 404.
To disable the page:
Sticky Sessions (opt-in)¶
HTTP sticky sessions let an RPC method bind a Python object — an open DuckDB cursor, a loaded model handle, a streaming LLM client — to the worker process that opened it, keyed by a signed session token that the client echoes in a VGI-Session header. Subsequent requests from the same client (inside a with_session_token() block) carry the header and the framework restores the object as ctx.session. Misroutes, expiries, and process restarts surface as a typed SessionLostError so apps can decide whether to retry or fail loudly.
The full wire contract — token format, header conventions, error kinds, the per-session serialization model, drain and crash semantics, load-balancer integration — lives in docs/sticky-sessions-spec.md. The quickstart:
from vgi_rpc import RpcServer, make_wsgi_app
server = RpcServer(MyService, MyServiceImpl())
app = make_wsgi_app(server, enable_sticky=True, sticky_default_ttl=300)
A method body opens a session by handing the framework a state object:
class MyServiceImpl:
def open_query(self, sql: str, ctx) -> str:
cursor = duckdb.connect().execute(sql)
ctx.open_session(cursor) # framework mints + returns the token
return "ok"
def next_rows(self, n: int, ctx) -> bytes:
return ctx.session.fetch_arrow_table(n).serialize().to_pybytes()
def close_query(self, ctx) -> None:
ctx.close_session() # closes cursor + evicts entry
On the client side, every session-using call lives inside a with_session_token() block — that's the opt-in signal the server requires (the leaked-session guard):
from vgi_rpc.http import http_connect
with http_connect(MyService, "http://localhost:8080") as conn, conn.with_session_token() as sess:
sess.open_query(sql="SELECT * FROM big")
rows = sess.next_rows(n=1000)
sess.close_query()
The block's exit fires a best-effort DELETE /vgi/__session__ so handle-bearing state gets released promptly. To stash a token across processes, call sess.detach() before the block exits — that hands the caller the token and suppresses the DELETE so the server-side session survives until its TTL or another caller closes it.
HTTP-only. Sticky machinery is not installed on pipe/subprocess/unix transports — those run as single processes where "sticky" is meaningless. ctx.open_session raises RuntimeError("sticky sessions not available on this transport") if called over a non-HTTP transport, so apps can detect-and-fall-back.
Client-driven routing via echo headers¶
Sticky LBs are not the only way to get a session-token-carrying request back to the worker that owns the session. With echo headers, the server tells the client (at session-open time) to attach an arbitrary set of headers on every subsequent request in the session, and the platform's edge proxy routes on those headers. Two helpers ship for Fly.io, where fly-force-instance-id is the proactive routing header fly-proxy honours:
from vgi_rpc import RpcServer
from vgi_rpc.http import make_wsgi_app
from vgi_rpc.http.fly import auto_server_id, fly_sticky_echo_headers
server = RpcServer(
MyService, MyServiceImpl(),
server_id=auto_server_id(), # ⇒ FLY_MACHINE_ID on Fly, random elsewhere
)
app = make_wsgi_app(
server,
enable_sticky=True,
sticky_echo_headers=fly_sticky_echo_headers(), # ⇒ {"fly-force-instance-id": <id>} on Fly, None elsewhere
)
On Fly the server emits VGI-Echo-fly-force-instance-id: <machine-id> on session-opening responses; the client captures it and replays fly-force-instance-id: <machine-id> on every subsequent request in the session; fly-proxy routes directly to the owning Machine. No LB configuration required.
Off Fly the helpers return None so the same code is a no-op — operators don't need conditional branches.
Generic API (for non-Fly platforms): pass any dict[str, str] as sticky_echo_headers and the server will emit them as VGI-Echo-<name> on the session-opening response. The client's with_session_token() view captures + replays automatically; sess.current_echo_headers() exposes the captured map for inspection or stashing.
API Reference¶
Server¶
make_wsgi_app
¶
make_wsgi_app(
server: RpcServer,
*,
prefix: str = "",
token_key: bytes | None = None,
max_response_bytes: int | None = None,
max_externalized_response_bytes: int | None = None,
max_request_bytes: int | None = None,
authenticate: (
Callable[[Request], AuthContext] | None
) = None,
proxy_proof_required: bool = False,
proxy_auth_headers: Sequence[str] | None = None,
cors_origins: str | Iterable[str] | None = None,
cors_max_age: int | None = 7200,
cors_resource_policy: str | None = "cross-origin",
upload_url_provider: UploadUrlProvider | None = None,
max_upload_bytes: int | None = None,
otel_config: object | None = None,
sentry_config: object | None = None,
token_ttl: int = 3600,
compression_level: int | None = 1,
enable_not_found_page: bool = True,
enable_landing_page: bool = True,
enable_describe_page: bool = True,
enable_health_endpoint: bool = True,
repo_url: str | None = None,
oauth_resource_metadata: (
OAuthResourceMetadata | None
) = None,
max_stream_response_bytes: int | None = None,
enable_sticky: bool = False,
sticky_default_ttl: float = 300.0,
sticky_echo_headers: Mapping[str, str] | None = None,
call_state_cache_entries: int = 4096,
introspect_resolver: TokenResolver | None = None,
introspect_principals: Iterable[str] | None = None,
introspect_rate_limit: int = 20
) -> App[Request, Response]
Create a Falcon WSGI app that serves RPC requests over HTTP.
| PARAMETER | DESCRIPTION |
|---|---|
server
|
The RpcServer instance to serve.
TYPE:
|
prefix
|
URL prefix for all RPC endpoints (default
TYPE:
|
token_key
|
AEAD (XChaCha20-Poly1305) master key for sealing stream
state tokens. When
TYPE:
|
max_response_bytes
|
HTTP body cap. Measured against the on-wire
body size only (
TYPE:
|
max_externalized_response_bytes
|
Cap on the external channel —
total bytes uploaded to external storage across one HTTP
response (one producer turn or one unary/exchange call).
Bounds how much data the client will end up fetching for one
RPC, regardless of how the framework chose to deliver it.
Default
TYPE:
|
max_request_bytes
|
When set, the value is advertised via the
TYPE:
|
authenticate
|
Optional callback that extracts an :class:
TYPE:
|
proxy_proof_required
|
Advertise
TYPE:
|
proxy_auth_headers
|
Names of headers a trusted reverse proxy must
inject for authentication to succeed. When any are known, every
401 this app emits carries
TYPE:
|
cors_origins
|
Allowed origins for CORS. Pass
TYPE:
|
cors_max_age
|
Value for the
TYPE:
|
cors_resource_policy
|
Value for the
TYPE:
|
upload_url_provider
|
Optional provider for generating pre-signed
upload URLs. When set, the
TYPE:
|
max_upload_bytes
|
When set (and
TYPE:
|
otel_config
|
Optional
TYPE:
|
sentry_config
|
Optional
TYPE:
|
token_ttl
|
Maximum age of stream state tokens in seconds. Tokens
older than this are rejected with HTTP 400. Default is 3600
(1 hour). Set to
TYPE:
|
compression_level
|
Zstandard compression level for HTTP request/
response bodies.
TYPE:
|
enable_not_found_page
|
When
TYPE:
|
enable_landing_page
|
When
TYPE:
|
enable_describe_page
|
When
TYPE:
|
enable_health_endpoint
|
When
TYPE:
|
repo_url
|
Optional URL to the service's source repository (e.g. a GitHub URL). When provided, a "Source repository" link appears on the landing page and describe page.
TYPE:
|
oauth_resource_metadata
|
Optional
TYPE:
|
max_stream_response_bytes
|
Deprecated alias for
TYPE:
|
enable_sticky
|
Master switch for HTTP sticky sessions. When
TYPE:
|
sticky_default_ttl
|
Default session TTL in seconds applied by
TYPE:
|
sticky_echo_headers
|
Optional mapping of headers the server tells
the client to echo on every subsequent request inside a
TYPE:
|
call_state_cache_entries
|
Size of the per-process call-state cache
(default 4096). The cache is a pure accelerator: a miss reopens
the call token the client echoed, so correctness never depends
on a hit. Setting it to
TYPE:
|
introspect_resolver
|
Enables
TYPE:
|
introspect_principals
|
Principals permitted to introspect. Required
whenever
TYPE:
|
introspect_rate_limit
|
Introspection requests allowed per caller per second (default 20). Bounds, rather than closes, the oracle an allowlisted-but-compromised caller still has.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
App[Request, Response]
|
A Falcon application with routes for unary and stream RPC calls. |
Source code in vgi_rpc/http/server/_factory.py
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 | |
serve_http
¶
serve_http(
server: RpcServer,
*,
host: str = "127.0.0.1",
port: int = 0,
max_response_bytes: int | None = None,
max_externalized_response_bytes: int | None = None,
max_stream_response_bytes: int | None = None,
max_request_bytes: int | None = None,
compression_level: int | None = 1,
authenticate: (
Callable[[Request], AuthContext] | None
) = None,
proxy_proof_required: bool = False,
token_key: bytes | None = None,
enable_sticky: bool = False,
sticky_default_ttl: float = 300.0,
sticky_echo_headers: Mapping[str, str] | None = None,
drain_grace_seconds: float = 30.0,
install_signal_handlers: bool = True,
threads: int | None = None,
call_state_cache_entries: int = 4096,
cors_origins: str | Iterable[str] | None = None,
cors_max_age: int | None = 7200,
cors_resource_policy: str | None = "cross-origin",
introspect_resolver: TokenResolver | None = None,
introspect_principals: Iterable[str] | None = None,
introspect_rate_limit: int = 20
) -> None
Serve an RpcServer over HTTP using waitress.
This is a convenience wrapper that combines :func:make_wsgi_app with
automatic port selection and waitress.serve.
The selected port is printed to stdout as PORT:<port> for
machine-readable discovery (e.g. by test harnesses or process managers).
When enable_sticky=True (and install_signal_handlers=True, the
default), this wrapper installs SIGTERM / SIGINT handlers that perform
a graceful drain:
- First signal: flip the registry's drain flag so subsequent
ctx.open_sessioncalls raise :class:~vgi_rpc.rpc.ServerDrainingError. Existing sessions continue to serve. - After
drain_grace_seconds(in a daemon timer thread): invokestate.close()on every live session andos._exit(0). - Second signal: skip the grace period and exit immediately.
For pre-fork servers (gunicorn, uwsgi) operators wire their own
worker_exit hooks. See :func:vgi_rpc.http.drain_handle and the
spec at docs/sticky-sessions-spec.md for the operator recipe.
| PARAMETER | DESCRIPTION |
|---|---|
server
|
The
TYPE:
|
host
|
Bind address (default
TYPE:
|
port
|
TCP port.
TYPE:
|
max_response_bytes
|
HTTP body cap; applies to every method. See
:func:
TYPE:
|
max_externalized_response_bytes
|
Cap on bytes uploaded to external
storage per HTTP response. See :func:
TYPE:
|
max_stream_response_bytes
|
Deprecated alias for
TYPE:
|
max_request_bytes
|
Advertised via
TYPE:
|
compression_level
|
zstd level for request/response bodies, or
TYPE:
|
authenticate
|
Per-request authenticate callback. See
:func:
TYPE:
|
proxy_proof_required
|
Advertise
TYPE:
|
token_key
|
Stable AEAD key for sealed state tokens. See
:func:
TYPE:
|
enable_sticky
|
See :func:
TYPE:
|
sticky_default_ttl
|
See :func:
TYPE:
|
sticky_echo_headers
|
See :func:
TYPE:
|
drain_grace_seconds
|
Seconds to wait between flipping the drain
flag and forcibly exiting on SIGTERM. Existing sessions get
this long to complete in-flight work. Default
TYPE:
|
install_signal_handlers
|
When
TYPE:
|
threads
|
Waitress worker threads, i.e. how many requests the server
handles concurrently before the rest queue.
TYPE:
|
call_state_cache_entries
|
Size of the per-process call-state cache;
TYPE:
|
cors_origins
|
Allowed CORS origins;
TYPE:
|
cors_max_age
|
Preflight cache lifetime in seconds. Only meaningful
when
TYPE:
|
cors_resource_policy
|
TYPE:
|
introspect_resolver
|
Enables the token-introspection endpoint. Absent
by default. See :func:
TYPE:
|
introspect_principals
|
Principals permitted to introspect; required
alongside
TYPE:
|
introspect_rate_limit
|
Introspection requests per caller per second.
See :func:
TYPE:
|
Source code in vgi_rpc/http/server/_serve.py
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 | |
Client¶
http_connect
¶
http_connect(
protocol: type[P],
base_url: str | None = None,
*,
prefix: str | None = None,
on_log: Callable[[Message], None] | None = None,
client: Client | _SyncTestClient | None = None,
external_location: ExternalLocationConfig | None = None,
ipc_validation: IpcValidation = FULL,
retry: HttpRetryConfig | None = None,
compression_level: int | None = 1
) -> Iterator[P]
Connect to an HTTP RPC server and yield a typed proxy.
| PARAMETER | DESCRIPTION |
|---|---|
protocol
|
The Protocol class defining the RPC interface.
TYPE:
|
base_url
|
Base URL of the server (e.g.
TYPE:
|
prefix
|
URL prefix matching the server's prefix. When
TYPE:
|
on_log
|
Optional callback for log messages from the server.
TYPE:
|
client
|
Optional HTTP client —
TYPE:
|
external_location
|
Optional ExternalLocationConfig for resolving and producing externalized batches.
TYPE:
|
ipc_validation
|
Validation level for incoming IPC batches.
TYPE:
|
retry
|
Optional retry configuration for transient HTTP failures.
When
TYPE:
|
compression_level
|
Zstandard compression level for request bodies.
TYPE:
|
| YIELDS | DESCRIPTION |
|---|---|
P
|
A typed RPC proxy supporting all methods defined on protocol. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If base_url is |
Source code in vgi_rpc/http/_client.py
http_introspect
¶
http_introspect(
base_url: str | None = None,
*,
prefix: str | None = None,
client: Client | _SyncTestClient | None = None,
ipc_validation: IpcValidation = FULL,
retry: HttpRetryConfig | None = None
) -> ServiceDescription
Send a __describe__ request over HTTP and return a ServiceDescription.
| PARAMETER | DESCRIPTION |
|---|---|
base_url
|
Base URL of the server (e.g.
TYPE:
|
prefix
|
URL prefix matching the server's prefix.
TYPE:
|
client
|
Optional HTTP client (
TYPE:
|
ipc_validation
|
Validation level for incoming IPC batches.
TYPE:
|
retry
|
Optional retry configuration for transient HTTP failures.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ServiceDescription
|
A |
| RAISES | DESCRIPTION |
|---|---|
RpcError
|
If the server does not support introspection or returns an error. |
ValueError
|
If base_url is |
Source code in vgi_rpc/http/_client.py
http_capabilities
¶
http_capabilities(
base_url: str | None = None,
*,
prefix: str | None = None,
client: Client | _SyncTestClient | None = None,
retry: HttpRetryConfig | None = None
) -> HttpServerCapabilities
Discover server capabilities via OPTIONS {prefix}/health.
The capability headers (VGI-Max-Request-Bytes,
VGI-Upload-URL-Support, VGI-Max-Upload-Bytes) are emitted on
every response, but the dedicated discovery target is /health
because it is mandatory in every implementation and exempt from
auth. The server may include Cache-Control: max-age=N on the
OPTIONS response; if so the returned HttpServerCapabilities
carries cache_expires_at so callers can refresh on expiry.
| PARAMETER | DESCRIPTION |
|---|---|
base_url
|
Base URL of the server (e.g.
TYPE:
|
prefix
|
URL prefix matching the server's prefix.
TYPE:
|
client
|
Optional HTTP client (
TYPE:
|
retry
|
Optional retry configuration for transient HTTP failures.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
HttpServerCapabilities
|
An |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If base_url is |
Source code in vgi_rpc/http/_client.py
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 | |
request_upload_urls
¶
request_upload_urls(
base_url: str | None = None,
*,
count: int = 1,
prefix: str | None = None,
client: Client | _SyncTestClient | None = None,
retry: HttpRetryConfig | None = None
) -> list[UploadUrl]
Request pre-signed upload URLs from the server's __upload_url__ endpoint.
The server must have been configured with an upload_url_provider
in make_wsgi_app().
| PARAMETER | DESCRIPTION |
|---|---|
base_url
|
Base URL of the server (e.g.
TYPE:
|
count
|
Number of upload URLs to request (default 1, max 100).
TYPE:
|
prefix
|
URL prefix matching the server's prefix.
TYPE:
|
client
|
Optional HTTP client (
TYPE:
|
retry
|
Optional retry configuration for transient HTTP failures.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[UploadUrl]
|
A list of |
| RAISES | DESCRIPTION |
|---|---|
RpcError
|
If the server does not support upload URLs (404) or returns an error. |
ValueError
|
If base_url is |
Source code in vgi_rpc/http/_client.py
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 | |
Capabilities¶
HttpServerCapabilities
dataclass
¶
HttpServerCapabilities(
max_request_bytes: int | None = None,
max_response_bytes: int | None = None,
max_externalized_response_bytes: int | None = None,
externalization_enabled: bool = False,
upload_url_support: bool = False,
max_upload_bytes: int | None = None,
supported_encodings: tuple[Encoding, ...] = (ZSTD,),
cache_expires_at: float | None = None,
sticky_enabled: bool = False,
sticky_default_ttl: int | None = None,
sticky_echo_headers: tuple[str, ...] = (),
)
Capabilities advertised by an HTTP RPC server.
Discovered via OPTIONS {prefix}/health (or any other route —
the headers are emitted on every response). The server may include
a Cache-Control: max-age=N header on the OPTIONS response; the
client honours that and refreshes when cache_expires_at lapses.
| ATTRIBUTE | DESCRIPTION |
|---|---|
max_request_bytes |
Maximum request body size the server advertises,
or
TYPE:
|
max_response_bytes |
HTTP body cap the server advertises for its
own responses, or
TYPE:
|
max_externalized_response_bytes |
Cap on per-response externalised
payload bytes, or
TYPE:
|
externalization_enabled |
TYPE:
|
upload_url_support |
Whether the server exposes
TYPE:
|
max_upload_bytes |
Maximum upload size the server advertises for
client-vended URLs, or
TYPE:
|
supported_encodings |
Content-encoding codecs the server can
decompress on request bodies and re-encode for responses.
Parsed from the
TYPE:
|
cache_expires_at |
Monotonic timestamp (
TYPE:
|
sticky_enabled |
Whether the server has
TYPE:
|
sticky_default_ttl |
Default session TTL in seconds when
TYPE:
|
sticky_echo_headers |
Header names the server tells the client to echo
on every subsequent session request. Parsed from the
comma-separated
TYPE:
|
Stream Session¶
HttpStreamSession
¶
HttpStreamSession(
client: Client | _SyncTestClient,
url_prefix: str,
method: str,
state_bytes: bytes | None,
output_schema: Schema,
on_log: Callable[[Message], None] | None = None,
*,
call_state_bytes: bytes | None = None,
external_config: ExternalLocationConfig | None = None,
ipc_validation: IpcValidation = FULL,
pending_batches: list[AnnotatedBatch] | None = None,
finished: bool = False,
header: object | None = None,
retry_config: HttpRetryConfig | None = None,
compression_level: int | None = None
)
Client-side handle for a stream over HTTP (both producer and exchange patterns).
For producer streams, use __iter__() — yields batches from batched
responses and follows continuation tokens transparently.
For exchange streams, use exchange() — sends an input batch and
receives an output batch.
Supports context manager protocol for convenience.
Initialize with HTTP client, method details, and initial state.
Source code in vgi_rpc/http/_client.py
typed_header
¶
Return the stream header narrowed to the expected type.
| PARAMETER | DESCRIPTION |
|---|---|
header_type
|
The expected header dataclass type.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
H
|
The header, typed as header_type. |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If the header is |
Source code in vgi_rpc/http/_client.py
exchange
¶
exchange(input_batch: AnnotatedBatch) -> AnnotatedBatch
Send an input batch and receive the output batch.
| PARAMETER | DESCRIPTION |
|---|---|
input_batch
|
The input batch to send.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AnnotatedBatch
|
The output batch from the server. |
| RAISES | DESCRIPTION |
|---|---|
RpcError
|
If the server reports an error or the stream has finished. |
Source code in vgi_rpc/http/_client.py
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 | |
__iter__
¶
__iter__() -> Iterator[AnnotatedBatch]
Iterate over output batches from a producer stream.
Yields pre-loaded batches from init, then follows continuation tokens.
Source code in vgi_rpc/http/_client.py
next_with_token
¶
next_with_token() -> (
tuple[AnnotatedBatch | None, bytes | None]
)
Read one producer batch and surface the worker's continuation token.
Reads exactly one data batch and returns it paired with the resume
token that continues the stream AFTER that batch — the worker's own
serialized producer state. A fresh session positioned at that token
(see :meth:seek_to_token) resumes on any node, which is the basis
for stateless, load-balanced relays that must not pin a scan to one
process.
Since a stream's state travels as two tokens (call + cursor), the
value returned here is the pair, encoded as one opaque blob by
:func:_encode_resume_token. Treat it as unstructured bytes; only
:meth:seek_to_token needs to know its shape.
Returns (None, None) at end-of-stream. Requires per-batch
continuation tokens (the default server behaviour — i.e. the worker
is not configured with max_response_bytes); raises
RuntimeError if a single response carries more than one data
batch (coarser-than-batch resume is not representable here).
Drives the same wire protocol as :meth:__iter__ but yields one
(batch, token) per call instead of auto-following the token. Do
not interleave with __iter__/exchange on the same session.
Source code in vgi_rpc/http/_client.py
seek_to_token
¶
Reposition a freshly-initialised session to resume from token.
Discards any init-preloaded batches and points the session at the
given resume token (as returned by :meth:next_with_token), so the
next :meth:next_with_token continues from exactly there. Used to
resume a scan on a new process/node — which is why the call token
travels inside the blob too: the node that serves the resumed turn
may never have seen this stream's /init.
Source code in vgi_rpc/http/_client.py
close
¶
cancel
¶
Signal the server to discard stream state and stop processing.
Sends a POST {prefix}/{method}/exchange carrying vgi_rpc.cancel
metadata alongside the current state token. The server invokes
state.on_cancel(ctx) (if defined) and releases the state.
Idempotent and best-effort: network failures are swallowed. After
cancel(), the session is marked finished; further exchange()
or iteration raises RpcError.
Source code in vgi_rpc/http/_client.py
__enter__
¶
__enter__() -> HttpStreamSession
__exit__
¶
Sticky Sessions¶
DrainHandle
dataclass
¶
DrainHandle(
drain: Callable[[], None],
shutdown: Callable[[], None],
is_draining: Callable[[], bool],
)
Operator-facing handle for triggering graceful drain on a sticky-enabled WSGI app.
Returned by :func:drain_handle when called against an app built by
:func:vgi_rpc.http.make_wsgi_app with enable_sticky=True. Provides
the two operations operators need to wire up SIGTERM handlers, pre-fork
worker-exit hooks (gunicorn worker_exit), or custom shutdown logic:
- :meth:
drain— flip the registry's drain flag so subsequentctx.open_sessioncalls raise :class:~vgi_rpc.rpc.ServerDrainingError. Existing-session calls continue to serve until TTL or explicit close. - :meth:
shutdown— invokestate.close()on every live session and clear the registry. Use after the operator-controlled grace period.
Both methods are idempotent and thread-safe (they delegate to
:class:_SessionRegistry's lock-guarded methods).
drain_handle
¶
drain_handle(
app: App[Request, Response],
) -> DrainHandle | None
Return a :class:DrainHandle for app, or None if sticky is not enabled.
Inspects the Falcon app's middleware tuple to find the
:class:_StickyMiddleware instance, then constructs closures over its
registry. Returns None cleanly for non-sticky apps so operator code
can branch with if (handle := drain_handle(app)) is not None: ....
Used by :func:vgi_rpc.http.serve_http for its SIGTERM wiring, and
exposed publicly so operators running under gunicorn / uwsgi / their
own WSGI launcher can wire equivalent shutdown hooks. See the spec at
docs/sticky-sessions-spec.md for the pre-fork worker-exit recipe.
Source code in vgi_rpc/http/server/_sticky.py
Fly.io quickstart¶
FLY_MACHINE_ID
module-attribute
¶
The current Fly Machine ID, or None outside Fly.
Read once at module import. Fly Machines have stable IDs that persist across restarts of the same Machine, so caching at import time is safe.
auto_server_id
¶
Return FLY_MACHINE_ID if running on Fly, else None.
Use as RpcServer(server_id=auto_server_id()) to make the session
token's stamped server identity match the Fly Machine ID. The
framework's session-token format embeds server_id length-prefixed,
so this works for any length of identifier — Fly Machine IDs are
14 hex characters today but the contract doesn't depend on that.
Returns None outside Fly so RpcServer falls back to its
default random 12-char hex server_id.
Source code in vgi_rpc/http/fly.py
fly_sticky_echo_headers
¶
Return {"fly-force-instance-id": FLY_MACHINE_ID} on Fly, else None.
Use as make_wsgi_app(..., sticky_echo_headers=fly_sticky_echo_headers()).
When a method opens a session via ctx.open_session(...) on Fly, the
server emits VGI-Echo-fly-force-instance-id: <machine-id> on the
response; the client captures and replays it as fly-force-instance-id
on every subsequent request in the same session, and fly-proxy routes
directly to the owning Machine.
Returns None outside Fly so passing this through unchanged is a
no-op in non-Fly environments — operators don't need a conditional.
Source code in vgi_rpc/http/fly.py
Testing¶
make_sync_client
¶
make_sync_client(
server: RpcServer,
*,
prefix: str = "",
token_key: bytes | None = None,
max_response_bytes: int | None = None,
max_externalized_response_bytes: int | None = None,
max_request_bytes: int | None = None,
max_stream_response_bytes: int | None = None,
authenticate: (
Callable[[Request], AuthContext] | None
) = None,
proxy_proof_required: bool = False,
proxy_auth_headers: Sequence[str] | None = None,
default_headers: dict[str, str] | None = None,
upload_url_provider: UploadUrlProvider | None = None,
max_upload_bytes: int | None = None,
otel_config: object | None = None,
sentry_config: object | None = None,
token_ttl: int = 3600,
compression_level: int | None = 1,
enable_not_found_page: bool = True,
enable_landing_page: bool = True,
enable_describe_page: bool = True,
enable_health_endpoint: bool = True,
repo_url: str | None = None,
oauth_resource_metadata: (
OAuthResourceMetadata | None
) = None,
enable_sticky: bool = False,
sticky_default_ttl: float = 300.0,
sticky_echo_headers: Mapping[str, str] | None = None,
call_state_cache_entries: int = 4096,
introspect_resolver: TokenResolver | None = None,
introspect_principals: Iterable[str] | None = None,
introspect_rate_limit: int = 20
) -> _SyncTestClient
Create a synchronous test client for an RpcServer.
Uses falcon.testing.TestClient internally — no real HTTP server needed.
| PARAMETER | DESCRIPTION |
|---|---|
server
|
The RpcServer to test.
TYPE:
|
prefix
|
URL prefix for RPC endpoints (default
TYPE:
|
token_key
|
AEAD key for sealing stream state tokens (see
TYPE:
|
max_response_bytes
|
See
TYPE:
|
max_externalized_response_bytes
|
See
TYPE:
|
max_request_bytes
|
See
TYPE:
|
max_stream_response_bytes
|
Deprecated alias for
TYPE:
|
authenticate
|
See
TYPE:
|
proxy_proof_required
|
See
TYPE:
|
proxy_auth_headers
|
See
TYPE:
|
default_headers
|
Headers merged into every request (e.g. auth tokens).
TYPE:
|
upload_url_provider
|
See
TYPE:
|
max_upload_bytes
|
See
TYPE:
|
otel_config
|
See
TYPE:
|
sentry_config
|
See
TYPE:
|
token_ttl
|
See
TYPE:
|
compression_level
|
See
TYPE:
|
enable_not_found_page
|
See
TYPE:
|
enable_landing_page
|
See
TYPE:
|
enable_describe_page
|
See
TYPE:
|
enable_health_endpoint
|
See
TYPE:
|
repo_url
|
See
TYPE:
|
oauth_resource_metadata
|
See
TYPE:
|
enable_sticky
|
See
TYPE:
|
sticky_default_ttl
|
See
TYPE:
|
sticky_echo_headers
|
See
TYPE:
|
call_state_cache_entries
|
See
TYPE:
|
introspect_resolver
|
See
TYPE:
|
introspect_principals
|
See
TYPE:
|
introspect_rate_limit
|
See
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
_SyncTestClient
|
A sync client that can be passed to |
Source code in vgi_rpc/http/_testing.py
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 | |