Factories
pyvider.rpcplugin.factories
¶
Factory functions for creating Pyvider RPC plugin components.
This module provides convenient factory functions for instantiating core components of the Pyvider RPC Plugin system, such as clients, servers, and protocols. These factories encapsulate common setup logic and promote consistent component creation.
Classes¶
Functions¶
create_basic_protocol
¶
Create a basic RPCPluginProtocol class for testing or simple use cases.
This factory creates a minimal protocol implementation that can be used when no specific gRPC services are needed. It's useful for: - Testing the plugin framework - Creating placeholder protocols - Demonstrating the protocol interface
Returns:
| Type | Description |
|---|---|
type[RPCPluginProtocol[Any, Any]]
|
A class that implements RPCPluginProtocol with minimal functionality. |
type[RPCPluginProtocol[Any, Any]]
|
The class can be instantiated with an optional service_name_override. |
Example
Note
The returned protocol class doesn't register any actual gRPC services. For production use, implement a custom protocol with real services.
Source code in pyvider/rpcplugin/factories.py
plugin_client
¶
Factory for creating an RPC plugin client instance.
This factory creates a client that can launch and communicate with a plugin subprocess. The client handles the complete lifecycle of the plugin process, including launching, handshake, and cleanup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
list[str]
|
Command and arguments to launch the plugin process. Example: ["python", "my_plugin.py"] or ["./my-plugin"] |
required |
config
|
dict[str, Any] | None
|
Optional configuration dictionary. Currently only supports passing environment variables to the plugin subprocess via the "env" key: config={"env": {"VAR": "value"}}. To configure client behavior, set environment variables in your own process before creating the client. |
None
|
Returns:
| Type | Description |
|---|---|
RPCPluginClient
|
An RPCPluginClient instance. You must call the async start() |
RPCPluginClient
|
method to launch the plugin and establish connection. |
Example
import asyncio
from pyvider.rpcplugin import plugin_client
async def main():
# Create client for a Python plugin (recommended: use context manager)
async with plugin_client(
command=["python", "path/to/plugin.py"],
config={"env": {"PLUGIN_LOG_LEVEL": "DEBUG"}} # Pass env vars to plugin
) as client:
# Launch plugin and establish connection
await client.start()
# Use the client's grpc_channel for RPC calls
stub = MyServiceStub(client.grpc_channel)
response = await stub.ProcessRequest(request)
# Gracefully shutdown
await client.shutdown_plugin()
# Client automatically closed on context exit
asyncio.run(main())
Advanced Example
# Configure plugin subprocess environment variables
# Note: config dict is used to pass environment variables to the plugin process
async with plugin_client(
command=["./my-secure-plugin"],
config={
"env": {
"PLUGIN_LOG_LEVEL": "DEBUG",
"PLUGIN_AUTO_MTLS": "true",
"MY_PLUGIN_API_KEY": "secret-key",
}
}
) as client:
await client.start()
# Use client...
# Automatically closed on context exit
To configure the CLIENT behavior (not the plugin subprocess),¶
set environment variables in your own process:¶
import os
# Configure client retry behavior
os.environ["PLUGIN_CLIENT_MAX_RETRIES"] = "5"
os.environ["PLUGIN_CLIENT_RETRY_ENABLED"] = "true"
os.environ["PLUGIN_CONNECTION_TIMEOUT"] = "30.0"
# Configure client-side mTLS
os.environ["PLUGIN_CLIENT_CERT"] = "file:///path/to/client.crt"
os.environ["PLUGIN_CLIENT_KEY"] = "file:///path/to/client.key"
async with plugin_client(command=["./my-secure-plugin"]) as client:
await client.start()
# Use client...
Manual Cleanup (Alternative):
# For cases where you need manual control over lifecycle
client = plugin_client(command=["python", "plugin.py"])
try:
await client.start()
# Use client...
finally:
await client.close()
Note
The client supports automatic retry with exponential backoff, subprocess management, stdio/stderr capture, and both Unix socket and TCP transports. The handshake protocol ensures secure communication via magic cookie validation.
Source code in pyvider/rpcplugin/factories.py
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 | |
plugin_protocol
¶
plugin_protocol(
protocol_class: type[PT_co] | None = None,
handler_class: type[RPCPluginHandler] | None = None,
service_name: str | None = None,
**kwargs: Any
) -> PT_co
Factory for creating an RPC plugin protocol instance.
This factory provides a convenient way to instantiate protocol objects with proper configuration. It can either create a custom protocol instance or fall back to a basic protocol for testing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
protocol_class
|
type[PT_co] | None
|
Optional custom protocol class to instantiate. If None, creates a BasicRPCPluginProtocol. |
None
|
handler_class
|
type[RPCPluginHandler] | None
|
Optional handler class (currently unused but reserved for future handler validation). |
None
|
service_name
|
str | None
|
Optional service name to override the default. Passed as 'service_name_override' to the protocol. |
None
|
**kwargs
|
Any
|
Additional keyword arguments passed to the protocol constructor. |
{}
|
Returns:
| Type | Description |
|---|---|
PT_co
|
An instance of the specified protocol class, or BasicRPCPluginProtocol |
PT_co
|
if no protocol_class was provided. |
Example
# Create a basic protocol with default settings
protocol = plugin_protocol()
# Create a basic protocol with custom service name
protocol = plugin_protocol(service_name="my.custom.service")
# Create an instance of a custom protocol class
from my_plugin import MyCustomProtocol
protocol = plugin_protocol(
protocol_class=MyCustomProtocol,
service_name="my.service.v1",
custom_option=True
)
# Use the protocol with a server
server = plugin_server(protocol=protocol, handler=handler)
Note
When using a custom protocol_class, ensure it accepts 'service_name_override' in its constructor if you want to use the service_name parameter.
Source code in pyvider/rpcplugin/factories.py
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 | |
plugin_server
¶
plugin_server(
protocol: ProtocolT,
handler: HandlerT,
transport: str = "unix",
transport_path: str | None = None,
host: str = "127.0.0.1",
port: int = 0,
config: dict[str, Any] | None = None,
) -> RPCPluginServer[_ServerT, ServerHandlerT, _TransportT]
Factory for creating an RPC plugin server instance.
This factory simplifies server creation by handling transport setup and configuration. It supports both Unix socket and TCP transports with sensible defaults for each platform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
protocol
|
ProtocolT
|
The protocol instance defining the RPC services. Usually created with plugin_protocol(). |
required |
handler
|
HandlerT
|
The service handler implementing the protocol's methods. This object will handle incoming RPC requests. |
required |
transport
|
str
|
Transport type to use. Either "unix" (default) or "tcp". Unix sockets are preferred for local IPC on Linux/macOS. |
'unix'
|
transport_path
|
str | None
|
For Unix sockets, the socket file path. If None, a temporary path is generated. |
None
|
host
|
str
|
For TCP transport, the bind address (default: "127.0.0.1"). |
'127.0.0.1'
|
port
|
int
|
For TCP transport, the port number (default: 0 for random). |
0
|
config
|
dict[str, Any] | None
|
Optional configuration dictionary to override defaults. Can include settings like timeouts, buffer sizes, etc. |
None
|
Returns:
| Type | Description |
|---|---|
RPCPluginServer[_ServerT, _HandlerT, _TransportT]
|
A configured RPCPluginServer instance ready to serve requests. |
RPCPluginServer[_ServerT, _HandlerT, _TransportT]
|
Call the serve() method to start accepting connections. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If an unsupported transport type is specified. |
Example
import asyncio
from pyvider.rpcplugin import plugin_server, plugin_protocol
class MyHandler:
async def process(self, request):
return {"result": "processed"}
async def main():
# Create server with Unix socket (default)
server = plugin_server(
protocol=plugin_protocol(),
handler=MyHandler()
)
# Or create TCP server
server = plugin_server(
protocol=plugin_protocol(),
handler=MyHandler(),
transport="tcp",
port=8080
)
# Start serving
await server.serve()
asyncio.run(main())
Note
The server will automatically handle the handshake protocol, including magic cookie validation and transport negotiation. For production use, consider enabling mTLS via configuration.
Source code in pyvider/rpcplugin/factories.py
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 | |