HTTP Transport¶
HTTP transport using Falcon (server) and httpx (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,
cors_origins: str | Iterable[str] | None = None,
cors_max_age: int | None = 7200,
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 = 3,
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
) -> 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:
|
cors_origins
|
Allowed origins for CORS. Pass
TYPE:
|
cors_max_age
|
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:
|
| 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
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 | |
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,
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
) -> 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:
|
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:
|
Source code in vgi_rpc/http/server/_serve.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
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 = 3
) -> 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
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 | |
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
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 | |
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
class-attribute
instance-attribute
¶
Whether the server has enable_sticky=True and supports VGI-Session.
sticky_default_ttl
class-attribute
instance-attribute
¶
Default session TTL in seconds when open_session is called without an explicit TTL.
sticky_echo_headers
class-attribute
instance-attribute
¶
Header names the server tells the client to echo on every subsequent session request.
Parsed from the comma-separated VGI-Sticky-Echo-Headers capability
header. Empty tuple when the server is sticky-enabled but has no
echo-header config (the default), or when the server is non-sticky.
Concrete values land on the _SessionView via captured
VGI-Echo-<name> response headers on the session-opening response;
this field exposes the names for introspection (LB configuration,
cross-language client implementations).
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,
*,
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
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 | |
__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
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,
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 = 3,
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
) -> _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:
|
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:
|
| 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 | |