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,
hosting_max_response_bytes: int | None = None,
preferred_response_bytes: int | None = None,
max_externalized_response_bytes: int | None = None,
max_request_bytes: int | None = None,
hosting_max_request_bytes: int | None = None,
authenticate: (
Callable[[Request], AuthContext] | None
) = None,
peer_identity_providers: Sequence[
PeerIdentityProvider
] = (),
peer_authentication_policy: (
PeerAuthenticationPolicy | None
) = None,
peer_service_name: str | None = None,
peer_resolution_timeout: float = 5.0,
peer_provider_concurrency: int = 64,
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,
identity_bearer: bool = True
) -> 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
|
Application HTTP response body cap. Combined
with
TYPE:
|
hosting_max_response_bytes
|
Optional response cap imposed by the hosting environment. It can only tighten the application cap.
TYPE:
|
preferred_response_bytes
|
Optional server-side batch-size target visible to worker code. It is clamped to the effective hard cap; it never weakens one.
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:
|
hosting_max_request_bytes
|
Optional hosting request cap. The effective
request cap is the minimum of this and
TYPE:
|
authenticate
|
Optional callback that extracts an :class:
TYPE:
|
peer_identity_providers
|
Evidence providers evaluated independently
from application authentication. Their immutable results are
exposed as
TYPE:
|
peer_authentication_policy
|
Optional policy composing resolved peer evidence with the existing authentication result.
TYPE:
|
peer_service_name
|
Destination service identifier supplied to peer evidence providers for destination-scoped authorization evidence.
TYPE:
|
peer_resolution_timeout
|
Total monotonic deadline, in seconds, for all peer evidence providers on one request.
TYPE:
|
peer_provider_concurrency
|
Maximum active provider callbacks per app. This hard bound also covers callbacks that ignore cancellation.
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:
|
identity_bearer
|
When the server hosts
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
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 | |
serve_http
¶
serve_http(
server: RpcServer,
*,
host: str = "127.0.0.1",
port: int = 0,
max_response_bytes: int | None = None,
hosting_max_response_bytes: int | None = None,
preferred_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,
hosting_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"
) -> 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:
|
hosting_max_response_bytes
|
See :func:
TYPE:
|
preferred_response_bytes
|
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:
|
hosting_max_request_bytes
|
See :func:
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:
|
Source code in vgi_rpc/http/server/_serve.py
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 | |
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,
accepted_max_response_bytes: (
int | None
) = _DEFAULT_ACCEPTED_MAX_RESPONSE_BYTES
) -> 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 replay-safe discovery and control requests, such as capability lookup and upload-URL allocation. RPC method dispatches and stream continuations are always single-attempt because their implementations may have side effects.
TYPE:
|
compression_level
|
Zstandard compression level for request bodies.
TYPE:
|
accepted_max_response_bytes
|
Hard response-body limit advertised on
every RPC request. The native Python default is 256 MiB. Pass
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
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 | |
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,
accepted_max_response_bytes: (
int | None
) = _DEFAULT_ACCEPTED_MAX_RESPONSE_BYTES,
external_location: ExternalLocationConfig | None = None
) -> ServiceDescription
Describe a server's primary protocol over HTTP.
Two round trips: list_protocols to learn what is hosted, then
describe on the first protocol that is not reflection itself. With a
server free to host several protocols there is no longer a single "the"
protocol to describe without first asking.
| 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:
|
accepted_max_response_bytes
|
Hard response limit sent with the request.
TYPE:
|
external_location
|
Configuration for fetching an externalized reply.
Needed against a server that externalizes: reflection is an
ordinary protocol now, so its replies are subject to the
transport's payload handling like any other method's. The old
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
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 | |
http_capabilities
¶
http_capabilities(
base_url: str | None = None,
*,
prefix: str | None = None,
client: Client | _SyncTestClient | None = None,
retry: HttpRetryConfig | None = None,
accepted_max_response_bytes: int | None = None
) -> HttpServerCapabilities
Discover server capabilities via OPTIONS {prefix}/health.
The capability headers (including VGI-Max-Request-Bytes and
VGI-Accept-Max-Response-Bytes-Support) 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:
|
accepted_max_response_bytes
|
Optional decoded response cap to advertise on the discovery request. Values must be between 65536 and 9007199254740991 inclusive.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
HttpServerCapabilities
|
An |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If base_url is |
Source code in vgi_rpc/http/_client.py
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 | |
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,
accepted_max_response_bytes: (
int | None
) = _DEFAULT_ACCEPTED_MAX_RESPONSE_BYTES
) -> 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:
|
accepted_max_response_bytes
|
Hard decoded response limit advertised after mandatory server capability discovery.
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
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 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 | |
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, ...] = (),
accept_max_response_bytes_support: bool = False,
)
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:
|
accept_max_response_bytes_support |
Whether the server honors the
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,
accepted_max_response_bytes: (
int | None
) = _DEFAULT_ACCEPTED_MAX_RESPONSE_BYTES,
capabilities: HttpServerCapabilities | None = None,
base_prefix: str | None = None
)
Client-side handle for a stream over HTTP (both producer and exchange patterns).
For producer streams, use __iter__() — yields one batch per lock-step
response 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
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 | |
__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
tick
¶
tick(
custom_metadata: KeyValueMetadata | None = None,
) -> AnnotatedBatch
Read one producer batch, attaching metadata to its continuation tick.
Metadata is sent only when a continuation request is required. If an init response already buffered a batch, consume that batch first.
| PARAMETER | DESCRIPTION |
|---|---|
custom_metadata
|
Optional application metadata to attach to the continuation tick.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AnnotatedBatch
|
The next producer batch. |
| RAISES | DESCRIPTION |
|---|---|
StopIteration
|
If the producer has finished. |
ValueError
|
If metadata is supplied while an init batch remains buffered. |
Source code in vgi_rpc/http/_client.py
next_with_token
¶
next_with_token(
custom_metadata: KeyValueMetadata | None = None,
) -> tuple[AnnotatedBatch | None, bytes | None]
Read one producer batch and surface the worker's continuation token.
custom_metadata is attached to the tick request that produces the
returned batch. It cannot be attached while consuming a batch already
buffered by the init response.
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. VGI-RPC lock-step requires
each response to carry at most one data batch; a response containing
more is rejected as a protocol violation.
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.
| PARAMETER | DESCRIPTION |
|---|---|
custom_metadata
|
Optional application metadata to attach to the continuation tick.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
AnnotatedBatch | None
|
The next batch and its opaque resume token, or |
bytes | None
|
at end-of-stream. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If a response contains multiple data batches. |
ValueError
|
If metadata is supplied while an init batch remains buffered. |
Source code in vgi_rpc/http/_client.py
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 | |
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,
hosting_max_response_bytes: int | None = None,
preferred_response_bytes: int | None = None,
max_externalized_response_bytes: int | None = None,
max_request_bytes: int | None = None,
hosting_max_request_bytes: int | None = None,
max_stream_response_bytes: int | None = None,
authenticate: (
Callable[[Request], AuthContext] | None
) = None,
peer_identity_providers: Sequence[
PeerIdentityProvider
] = (),
peer_authentication_policy: (
PeerAuthenticationPolicy | None
) = None,
peer_service_name: str | None = None,
peer_resolution_timeout: float = 5.0,
peer_provider_concurrency: int = 64,
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
) -> _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:
|
hosting_max_response_bytes
|
See
TYPE:
|
preferred_response_bytes
|
See
TYPE:
|
max_externalized_response_bytes
|
See
TYPE:
|
max_request_bytes
|
See
TYPE:
|
hosting_max_request_bytes
|
See
TYPE:
|
max_stream_response_bytes
|
Deprecated alias for
TYPE:
|
authenticate
|
See
TYPE:
|
peer_identity_providers
|
See
TYPE:
|
peer_authentication_policy
|
See
TYPE:
|
peer_service_name
|
See
TYPE:
|
peer_resolution_timeout
|
See
TYPE:
|
peer_provider_concurrency
|
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:
|
| RETURNS | DESCRIPTION |
|---|---|
_SyncTestClient
|
A sync client that can be passed to |
Source code in vgi_rpc/http/_testing.py
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 | |