0
# Channel Management
1
2
Channel management provides client-side connection handling with support for secure and insecure connections, connectivity monitoring, interceptor chains, and comprehensive configuration options for production deployments.
3
4
## Capabilities
5
6
### Channel Creation
7
8
Creates channels for client-side RPC communication with support for insecure and secure connections, including SSL/TLS, ALTS, and custom credentials.
9
10
```python { .api }
11
def insecure_channel(target: str, options=None, compression=None) -> Channel:
12
"""
13
Creates an insecure Channel to a server.
14
15
Parameters:
16
- target: The server address (e.g., 'localhost:50051', 'dns:///example.com:443')
17
- options: Optional list of key-value pairs for channel configuration
18
- compression: Optional compression method (grpc.compression.Gzip, etc.)
19
20
Returns:
21
Channel: A thread-safe Channel object for making RPCs
22
"""
23
24
def secure_channel(target: str, credentials: ChannelCredentials, options=None, compression=None) -> Channel:
25
"""
26
Creates a secure Channel to a server.
27
28
Parameters:
29
- target: The server address
30
- credentials: A ChannelCredentials instance for authentication
31
- options: Optional list of key-value pairs for channel configuration
32
- compression: Optional compression method
33
34
Returns:
35
Channel: A thread-safe secure Channel object
36
37
Raises:
38
ValueError: If called with insecure credentials
39
"""
40
```
41
42
**Usage Examples:**
43
44
```python
45
# Basic insecure channel
46
channel = grpc.insecure_channel('localhost:50051')
47
48
# Secure channel with SSL
49
credentials = grpc.ssl_channel_credentials()
50
secure_chan = grpc.secure_channel('secure-server.com:443', credentials)
51
52
# Channel with custom options
53
options = [
54
('grpc.keepalive_time_ms', 30000),
55
('grpc.max_receive_message_length', 4 * 1024 * 1024),
56
]
57
channel = grpc.insecure_channel('localhost:50051', options=options)
58
59
# Channel with compression
60
channel = grpc.insecure_channel('localhost:50051', compression=grpc.compression.Gzip)
61
```
62
63
### Channel Interception
64
65
Applies interceptor chains to channels for cross-cutting concerns like logging, metrics, authentication, and request/response transformation.
66
67
```python { .api }
68
def intercept_channel(channel: Channel, *interceptors) -> Channel:
69
"""
70
Intercepts a channel through a set of interceptors.
71
72
Parameters:
73
- channel: A Channel object to intercept
74
- interceptors: Zero or more interceptor objects
75
76
Returns:
77
Channel: A Channel that applies interceptors to each invocation
78
79
Raises:
80
TypeError: If interceptor doesn't implement required interfaces
81
"""
82
```
83
84
**Usage Example:**
85
86
```python
87
class LoggingInterceptor(grpc.UnaryUnaryClientInterceptor):
88
def intercept_unary_unary(self, continuation, client_call_details, request):
89
print(f"Calling {client_call_details.method}")
90
response = continuation(client_call_details, request)
91
print(f"Received response")
92
return response
93
94
# Apply interceptor to channel
95
channel = grpc.insecure_channel('localhost:50051')
96
intercepted_channel = grpc.intercept_channel(channel, LoggingInterceptor())
97
```
98
99
### Channel Readiness
100
101
Monitors channel connectivity state and provides futures for readiness notification, useful for connection pooling and health checking.
102
103
```python { .api }
104
def channel_ready_future(channel: Channel) -> Future:
105
"""
106
Creates a Future that tracks when a Channel is ready.
107
108
Parameters:
109
- channel: A Channel object to monitor
110
111
Returns:
112
Future: A Future that completes when channel reaches READY state
113
114
Note:
115
Cancelling the Future does not affect the channel's state machine
116
"""
117
```
118
119
**Usage Example:**
120
121
```python
122
channel = grpc.insecure_channel('localhost:50051')
123
ready_future = grpc.channel_ready_future(channel)
124
125
# Wait for channel to be ready (blocking)
126
try:
127
ready_future.result(timeout=5.0)
128
print("Channel is ready")
129
except grpc.FutureTimeoutError:
130
print("Channel not ready within timeout")
131
```
132
133
### Channel Interface
134
135
Core channel interface providing RPC invocation methods and connectivity management.
136
137
```python { .api }
138
class Channel(abc.ABC):
139
"""
140
Affords RPC invocation via generic methods on client-side.
141
Supports context manager protocol for automatic cleanup.
142
"""
143
144
def subscribe(self, callback, try_to_connect=False):
145
"""
146
Subscribe to this Channel's connectivity state machine.
147
148
Parameters:
149
- callback: Callable invoked with ChannelConnectivity argument
150
- try_to_connect: Whether channel should attempt immediate connection
151
"""
152
153
def unsubscribe(self, callback):
154
"""
155
Unsubscribes a callback from connectivity notifications.
156
157
Parameters:
158
- callback: Previously registered callback function
159
"""
160
161
def unary_unary(self, method: str, request_serializer=None, response_deserializer=None, _registered_method=False) -> UnaryUnaryMultiCallable:
162
"""
163
Creates a UnaryUnaryMultiCallable for a unary-unary method.
164
165
Parameters:
166
- method: The name of the RPC method (e.g., '/service.Method')
167
- request_serializer: Optional serializer for request messages
168
- response_deserializer: Optional deserializer for response messages
169
- _registered_method: Internal parameter for registered methods
170
171
Returns:
172
UnaryUnaryMultiCallable: Object for making unary-unary calls
173
"""
174
175
def unary_stream(self, method: str, request_serializer=None, response_deserializer=None, _registered_method=False) -> UnaryStreamMultiCallable:
176
"""Creates a UnaryStreamMultiCallable for a unary-stream method."""
177
178
def stream_unary(self, method: str, request_serializer=None, response_deserializer=None, _registered_method=False) -> StreamUnaryMultiCallable:
179
"""Creates a StreamUnaryMultiCallable for a stream-unary method."""
180
181
def stream_stream(self, method: str, request_serializer=None, response_deserializer=None, _registered_method=False) -> StreamStreamMultiCallable:
182
"""Creates a StreamStreamMultiCallable for a stream-stream method."""
183
184
def close(self):
185
"""
186
Closes this Channel and releases all resources.
187
Terminates all active RPCs and prevents new ones.
188
This method is idempotent.
189
"""
190
191
def __enter__(self):
192
"""Enters the runtime context for context manager usage."""
193
194
def __exit__(self, exc_type, exc_val, exc_tb):
195
"""Exits the runtime context and closes the channel."""
196
```
197
198
**Usage Examples:**
199
200
```python
201
# Context manager usage (recommended)
202
with grpc.insecure_channel('localhost:50051') as channel:
203
stub = MyServiceStub(channel)
204
response = stub.MyMethod(request)
205
# Channel automatically closed
206
207
# Manual lifecycle management
208
channel = grpc.insecure_channel('localhost:50051')
209
try:
210
stub = MyServiceStub(channel)
211
response = stub.MyMethod(request)
212
finally:
213
channel.close()
214
215
# Connectivity monitoring
216
def connectivity_callback(connectivity):
217
print(f"Channel state: {connectivity}")
218
219
channel = grpc.insecure_channel('localhost:50051')
220
channel.subscribe(connectivity_callback, try_to_connect=True)
221
```
222
223
### Channel Options
224
225
Common channel configuration options for production deployments:
226
227
```python
228
# Keepalive settings
229
('grpc.keepalive_time_ms', 30000),
230
('grpc.keepalive_timeout_ms', 5000),
231
('grpc.keepalive_permit_without_calls', True),
232
233
# Message size limits
234
('grpc.max_send_message_length', 4 * 1024 * 1024),
235
('grpc.max_receive_message_length', 4 * 1024 * 1024),
236
237
# Connection settings
238
('grpc.max_connection_idle_ms', 300000),
239
('grpc.max_connection_age_ms', 600000),
240
('grpc.http2.max_pings_without_data', 0),
241
242
# Load balancing
243
('grpc.lb_policy_name', 'round_robin'),
244
('grpc.service_config', '{"loadBalancingConfig": [{"round_robin":{}}]}'),
245
```
246
247
## Types
248
249
```python { .api }
250
class ChannelConnectivity(enum.Enum):
251
"""Channel connectivity states."""
252
IDLE = ... # Channel is idle
253
CONNECTING = ... # Channel is connecting
254
READY = ... # Channel is ready to conduct RPCs
255
TRANSIENT_FAILURE = ... # Channel has seen a recoverable failure
256
SHUTDOWN = ... # Channel has seen an unrecoverable failure
257
```