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.3.2, created at 2023-12-08 06:45 +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, generic_rpc_handlers: Sequence[grpc.GenericRpcHandler] 

34 ) -> 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( 

63 self, address: str, server_credentials: grpc.ServerCredentials 

64 ) -> int: 

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

66 

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

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

69 

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

71 

72 Args: 

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

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

75 runtime will choose a port. 

76 server_credentials: A ServerCredentials object. 

77 

78 Returns: 

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

80 """ 

81 

82 @abc.abstractmethod 

83 async def start(self) -> None: 

84 """Starts this Server. 

85 

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

87 """ 

88 

89 @abc.abstractmethod 

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

91 """Stops this Server. 

92 

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

94 all cases. 

95 

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

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

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

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

100 handler terminates. 

101 

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

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

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

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

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

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

108 

109 Args: 

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

111 """ 

112 

113 @abc.abstractmethod 

114 async def wait_for_termination( 

115 self, timeout: Optional[float] = None 

116 ) -> bool: 

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

118 

119 This is an EXPERIMENTAL API. 

120 

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

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

123 

124 1) The server is stopped or terminated; 

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

126 

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

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

129 

130 Args: 

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

132 operation in seconds. 

133 

134 Returns: 

135 A bool indicates if the operation times out. 

136 """ 

137 

138 

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

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

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

142 

143 @abc.abstractmethod 

144 async def read(self) -> RequestType: 

145 """Reads one message from the RPC. 

146 

147 Only one read operation is allowed simultaneously. 

148 

149 Returns: 

150 A response message of the RPC. 

151 

152 Raises: 

153 An RpcError exception if the read failed. 

154 """ 

155 

156 @abc.abstractmethod 

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

158 """Writes one message to the RPC. 

159 

160 Only one write operation is allowed simultaneously. 

161 

162 Raises: 

163 An RpcError exception if the write failed. 

164 """ 

165 

166 @abc.abstractmethod 

167 async def send_initial_metadata( 

168 self, initial_metadata: MetadataType 

169 ) -> None: 

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

171 

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

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

174 

175 Args: 

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

177 """ 

178 

179 @abc.abstractmethod 

180 async def abort( 

181 self, 

182 code: grpc.StatusCode, 

183 details: str = "", 

184 trailing_metadata: MetadataType = tuple(), 

185 ) -> NoReturn: 

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

187 

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

189 ones. 

190 

191 Args: 

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

193 It must not be StatusCode.OK. 

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

195 termination of the RPC. 

196 trailing_metadata: A sequence of tuple represents the trailing 

197 :term:`metadata`. 

198 

199 Raises: 

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

201 RPC to the gRPC runtime. 

202 """ 

203 

204 @abc.abstractmethod 

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

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

207 

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

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

210 

211 Args: 

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

213 """ 

214 

215 @abc.abstractmethod 

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

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

218 

219 Returns: 

220 The invocation :term:`metadata`. 

221 """ 

222 

223 @abc.abstractmethod 

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

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

226 

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

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

229 

230 Args: 

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

232 """ 

233 

234 @abc.abstractmethod 

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

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

237 

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

239 no details to transmit. 

240 

241 Args: 

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

243 termination of the RPC. 

244 """ 

245 

246 @abc.abstractmethod 

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

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

249 

250 Args: 

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

252 grpc.compression.Gzip. 

253 """ 

254 

255 @abc.abstractmethod 

256 def disable_next_message_compression(self) -> None: 

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

258 

259 This method will override any compression configuration set during 

260 server creation or set on the call. 

261 """ 

262 

263 @abc.abstractmethod 

264 def peer(self) -> str: 

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

266 

267 Returns: 

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

269 The string format is determined by gRPC runtime. 

270 """ 

271 

272 @abc.abstractmethod 

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

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

275 

276 Equivalent to 

277 servicer_context.auth_context().get(servicer_context.peer_identity_key()) 

278 

279 Returns: 

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

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

282 """ 

283 

284 @abc.abstractmethod 

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

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

287 

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

289 used to identify an SSL peer. 

290 

291 Returns: 

292 The auth property (string) that indicates the 

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

294 """ 

295 

296 @abc.abstractmethod 

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

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

299 

300 Returns: 

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

302 """ 

303 

304 def time_remaining(self) -> float: 

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

306 

307 Returns: 

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

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

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

311 """ 

312 

313 def trailing_metadata(self): 

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

315 

316 This is an EXPERIMENTAL API. 

317 

318 Returns: 

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

320 """ 

321 raise NotImplementedError() 

322 

323 def code(self): 

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

325 

326 This is an EXPERIMENTAL API. 

327 

328 Returns: 

329 The StatusCode value for the RPC. 

330 """ 

331 raise NotImplementedError() 

332 

333 def details(self): 

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

335 

336 This is an EXPERIMENTAL API. 

337 

338 Returns: 

339 The details string of the RPC. 

340 """ 

341 raise NotImplementedError() 

342 

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

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

345 

346 This is an EXPERIMENTAL API. 

347 

348 Args: 

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

350 object as its only argument. 

351 """ 

352 

353 def cancelled(self) -> bool: 

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

355 

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

357 

358 This is an EXPERIMENTAL API. 

359 

360 Returns: 

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

362 """ 

363 

364 def done(self) -> bool: 

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

366 

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

368 

369 This is an EXPERIMENTAL API. 

370 

371 Returns: 

372 A bool indicates if the RPC is done. 

373 """