Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/grpc/aio/_base_server.py: 95%

61 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-06 06:03 +0000

1# Copyright 2020 The gRPC Authors 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14"""Abstract base classes for server-side classes.""" 

15 

16import abc 

17from typing import Generic, Iterable, Mapping, NoReturn, Optional, Sequence 

18 

19import grpc 

20 

21from ._metadata import Metadata 

22from ._typing import DoneCallbackType 

23from ._typing import MetadataType 

24from ._typing import RequestType 

25from ._typing import ResponseType 

26 

27 

28class Server(abc.ABC): 

29 """Serves RPCs.""" 

30 

31 @abc.abstractmethod 

32 def add_generic_rpc_handlers( 

33 self, 

34 generic_rpc_handlers: Sequence[grpc.GenericRpcHandler]) -> None: 

35 """Registers GenericRpcHandlers with this Server. 

36 

37 This method is only safe to call before the server is started. 

38 

39 Args: 

40 generic_rpc_handlers: A sequence of GenericRpcHandlers that will be 

41 used to service RPCs. 

42 """ 

43 

44 @abc.abstractmethod 

45 def add_insecure_port(self, address: str) -> int: 

46 """Opens an insecure port for accepting RPCs. 

47 

48 A port is a communication endpoint that used by networking protocols, 

49 like TCP and UDP. To date, we only support TCP. 

50 

51 This method may only be called before starting the server. 

52 

53 Args: 

54 address: The address for which to open a port. If the port is 0, 

55 or not specified in the address, then the gRPC runtime will choose a port. 

56 

57 Returns: 

58 An integer port on which the server will accept RPC requests. 

59 """ 

60 

61 @abc.abstractmethod 

62 def add_secure_port(self, address: str, 

63 server_credentials: grpc.ServerCredentials) -> int: 

64 """Opens a secure port for accepting RPCs. 

65 

66 A port is a communication endpoint that used by networking protocols, 

67 like TCP and UDP. To date, we only support TCP. 

68 

69 This method may only be called before starting the server. 

70 

71 Args: 

72 address: The address for which to open a port. 

73 if the port is 0, or not specified in the address, then the gRPC 

74 runtime will choose a port. 

75 server_credentials: A ServerCredentials object. 

76 

77 Returns: 

78 An integer port on which the server will accept RPC requests. 

79 """ 

80 

81 @abc.abstractmethod 

82 async def start(self) -> None: 

83 """Starts this Server. 

84 

85 This method may only be called once. (i.e. it is not idempotent). 

86 """ 

87 

88 @abc.abstractmethod 

89 async def stop(self, grace: Optional[float]) -> None: 

90 """Stops this Server. 

91 

92 This method immediately stops the server from servicing new RPCs in 

93 all cases. 

94 

95 If a grace period is specified, this method returns immediately and all 

96 RPCs active at the end of the grace period are aborted. If a grace 

97 period is not specified (by passing None for grace), all existing RPCs 

98 are aborted immediately and this method blocks until the last RPC 

99 handler terminates. 

100 

101 This method is idempotent and may be called at any time. Passing a 

102 smaller grace value in a subsequent call will have the effect of 

103 stopping the Server sooner (passing None will have the effect of 

104 stopping the server immediately). Passing a larger grace value in a 

105 subsequent call will not have the effect of stopping the server later 

106 (i.e. the most restrictive grace value is used). 

107 

108 Args: 

109 grace: A duration of time in seconds or None. 

110 """ 

111 

112 @abc.abstractmethod 

113 async def wait_for_termination(self, 

114 timeout: Optional[float] = None) -> bool: 

115 """Continues current coroutine once the server stops. 

116 

117 This is an EXPERIMENTAL API. 

118 

119 The wait will not consume computational resources during blocking, and 

120 it will block until one of the two following conditions are met: 

121 

122 1) The server is stopped or terminated; 

123 2) A timeout occurs if timeout is not `None`. 

124 

125 The timeout argument works in the same way as `threading.Event.wait()`. 

126 https://docs.python.org/3/library/threading.html#threading.Event.wait 

127 

128 Args: 

129 timeout: A floating point number specifying a timeout for the 

130 operation in seconds. 

131 

132 Returns: 

133 A bool indicates if the operation times out. 

134 """ 

135 

136 

137# pylint: disable=too-many-public-methods 

138class ServicerContext(Generic[RequestType, ResponseType], abc.ABC): 

139 """A context object passed to method implementations.""" 

140 

141 @abc.abstractmethod 

142 async def read(self) -> RequestType: 

143 """Reads one message from the RPC. 

144 

145 Only one read operation is allowed simultaneously. 

146 

147 Returns: 

148 A response message of the RPC. 

149 

150 Raises: 

151 An RpcError exception if the read failed. 

152 """ 

153 

154 @abc.abstractmethod 

155 async def write(self, message: ResponseType) -> None: 

156 """Writes one message to the RPC. 

157 

158 Only one write operation is allowed simultaneously. 

159 

160 Raises: 

161 An RpcError exception if the write failed. 

162 """ 

163 

164 @abc.abstractmethod 

165 async def send_initial_metadata(self, 

166 initial_metadata: MetadataType) -> None: 

167 """Sends the initial metadata value to the client. 

168 

169 This method need not be called by implementations if they have no 

170 metadata to add to what the gRPC runtime will transmit. 

171 

172 Args: 

173 initial_metadata: The initial :term:`metadata`. 

174 """ 

175 

176 @abc.abstractmethod 

177 async def abort( 

178 self, 

179 code: grpc.StatusCode, 

180 details: str = '', 

181 trailing_metadata: MetadataType = tuple()) -> NoReturn: 

182 """Raises an exception to terminate the RPC with a non-OK status. 

183 

184 The code and details passed as arguments will supercede any existing 

185 ones. 

186 

187 Args: 

188 code: A StatusCode object to be sent to the client. 

189 It must not be StatusCode.OK. 

190 details: A UTF-8-encodable string to be sent to the client upon 

191 termination of the RPC. 

192 trailing_metadata: A sequence of tuple represents the trailing 

193 :term:`metadata`. 

194 

195 Raises: 

196 Exception: An exception is always raised to signal the abortion the 

197 RPC to the gRPC runtime. 

198 """ 

199 

200 @abc.abstractmethod 

201 def set_trailing_metadata(self, trailing_metadata: MetadataType) -> None: 

202 """Sends the trailing metadata for the RPC. 

203 

204 This method need not be called by implementations if they have no 

205 metadata to add to what the gRPC runtime will transmit. 

206 

207 Args: 

208 trailing_metadata: The trailing :term:`metadata`. 

209 """ 

210 

211 @abc.abstractmethod 

212 def invocation_metadata(self) -> Optional[Metadata]: 

213 """Accesses the metadata sent by the client. 

214 

215 Returns: 

216 The invocation :term:`metadata`. 

217 """ 

218 

219 @abc.abstractmethod 

220 def set_code(self, code: grpc.StatusCode) -> None: 

221 """Sets the value to be used as status code upon RPC completion. 

222 

223 This method need not be called by method implementations if they wish 

224 the gRPC runtime to determine the status code of the RPC. 

225 

226 Args: 

227 code: A StatusCode object to be sent to the client. 

228 """ 

229 

230 @abc.abstractmethod 

231 def set_details(self, details: str) -> None: 

232 """Sets the value to be used the as detail string upon RPC completion. 

233 

234 This method need not be called by method implementations if they have 

235 no details to transmit. 

236 

237 Args: 

238 details: A UTF-8-encodable string to be sent to the client upon 

239 termination of the RPC. 

240 """ 

241 

242 @abc.abstractmethod 

243 def set_compression(self, compression: grpc.Compression) -> None: 

244 """Set the compression algorithm to be used for the entire call. 

245 

246 Args: 

247 compression: An element of grpc.compression, e.g. 

248 grpc.compression.Gzip. 

249 """ 

250 

251 @abc.abstractmethod 

252 def disable_next_message_compression(self) -> None: 

253 """Disables compression for the next response message. 

254 

255 This method will override any compression configuration set during 

256 server creation or set on the call. 

257 """ 

258 

259 @abc.abstractmethod 

260 def peer(self) -> str: 

261 """Identifies the peer that invoked the RPC being serviced. 

262 

263 Returns: 

264 A string identifying the peer that invoked the RPC being serviced. 

265 The string format is determined by gRPC runtime. 

266 """ 

267 

268 @abc.abstractmethod 

269 def peer_identities(self) -> Optional[Iterable[bytes]]: 

270 """Gets one or more peer identity(s). 

271 

272 Equivalent to 

273 servicer_context.auth_context().get(servicer_context.peer_identity_key()) 

274 

275 Returns: 

276 An iterable of the identities, or None if the call is not 

277 authenticated. Each identity is returned as a raw bytes type. 

278 """ 

279 

280 @abc.abstractmethod 

281 def peer_identity_key(self) -> Optional[str]: 

282 """The auth property used to identify the peer. 

283 

284 For example, "x509_common_name" or "x509_subject_alternative_name" are 

285 used to identify an SSL peer. 

286 

287 Returns: 

288 The auth property (string) that indicates the 

289 peer identity, or None if the call is not authenticated. 

290 """ 

291 

292 @abc.abstractmethod 

293 def auth_context(self) -> Mapping[str, Iterable[bytes]]: 

294 """Gets the auth context for the call. 

295 

296 Returns: 

297 A map of strings to an iterable of bytes for each auth property. 

298 """ 

299 

300 def time_remaining(self) -> float: 

301 """Describes the length of allowed time remaining for the RPC. 

302 

303 Returns: 

304 A nonnegative float indicating the length of allowed time in seconds 

305 remaining for the RPC to complete before it is considered to have 

306 timed out, or None if no deadline was specified for the RPC. 

307 """ 

308 

309 def trailing_metadata(self): 

310 """Access value to be used as trailing metadata upon RPC completion. 

311 

312 This is an EXPERIMENTAL API. 

313 

314 Returns: 

315 The trailing :term:`metadata` for the RPC. 

316 """ 

317 raise NotImplementedError() 

318 

319 def code(self): 

320 """Accesses the value to be used as status code upon RPC completion. 

321 

322 This is an EXPERIMENTAL API. 

323 

324 Returns: 

325 The StatusCode value for the RPC. 

326 """ 

327 raise NotImplementedError() 

328 

329 def details(self): 

330 """Accesses the value to be used as detail string upon RPC completion. 

331 

332 This is an EXPERIMENTAL API. 

333 

334 Returns: 

335 The details string of the RPC. 

336 """ 

337 raise NotImplementedError() 

338 

339 def add_done_callback(self, callback: DoneCallbackType) -> None: 

340 """Registers a callback to be called on RPC termination. 

341 

342 This is an EXPERIMENTAL API. 

343 

344 Args: 

345 callback: A callable object will be called with the servicer context 

346 object as its only argument. 

347 """ 

348 

349 def cancelled(self) -> bool: 

350 """Return True if the RPC is cancelled. 

351 

352 The RPC is cancelled when the cancellation was requested with cancel(). 

353 

354 This is an EXPERIMENTAL API. 

355 

356 Returns: 

357 A bool indicates whether the RPC is cancelled or not. 

358 """ 

359 

360 def done(self) -> bool: 

361 """Return True if the RPC is done. 

362 

363 An RPC is done if the RPC is completed, cancelled or aborted. 

364 

365 This is an EXPERIMENTAL API. 

366 

367 Returns: 

368 A bool indicates if the RPC is done. 

369 """