1414
1515from __future__ import annotations
1616
17+ import inspect
1718import json
1819from collections .abc import Awaitable
19- from typing import Any , Callable , Dict , Optional , Type , TypeVar
20+ from typing import Any , Callable , Dict , Optional , Tuple , Type , TypeVar
2021from urllib .parse import urlparse
2122
2223import aiohttp
4142 404 : ServerErrorCode .NOT_FOUND ,
4243 409 : ServerErrorCode .ALREADY_EXISTS ,
4344 429 : ServerErrorCode .RESOURCE_EXHAUSTED ,
45+ 499 : ServerErrorCode .CANCELED ,
4446 501 : ServerErrorCode .UNIMPLEMENTED ,
47+ 502 : ServerErrorCode .UNAVAILABLE ,
4548 503 : ServerErrorCode .UNAVAILABLE ,
4649 504 : ServerErrorCode .DEADLINE_EXCEEDED ,
4750}
@@ -97,8 +100,8 @@ async def request(
97100 ) -> M :
98101 """Calls a generated operation and parses its JSON (or its `field`) into `response_class`.
99102 A parameter at its protobuf default (`""`, `0`) is left unset."""
100- data = await self ._call (operation = operation , headers = headers , params = params )
101- return _parse (data .get (field ) if field else data , response_class )
103+ data , status = await self ._call (operation = operation , headers = headers , params = params )
104+ return _parse (data .get (field ) if field else data , response_class , status )
102105
103106 async def list (
104107 self ,
@@ -113,36 +116,64 @@ async def list(
113116 ) -> M :
114117 """Calls a generated list operation for one page: its `items` and `pageInfo` become the
115118 protocol response's `items` field and `next_page_token`."""
116- data = await self ._call (
119+ data , status = await self ._call (
117120 operation = operation ,
118121 headers = headers ,
119122 # A limit of zero or below leaves the page size to the server.
120123 params = {"page_cursor" : page_token , "page_page_size" : max (limit , 0 ), ** params },
121124 )
122125 next_page = (data .get ("pageInfo" ) or {}).get ("nextCursor" , "" )
123- return _parse ({items : data .get ("items" ), "nextPageToken" : next_page }, response_class )
126+ page = {items : data .get ("items" ), "nextPageToken" : next_page }
127+ return _parse (page , response_class , status )
124128
125129 async def _call (
126130 self ,
127131 * ,
128132 operation : Callable [..., Awaitable [aiohttp .ClientResponse ]],
129133 headers : Dict [str , str ],
130134 params : Dict [str , Any ],
131- ) -> Dict [str , Any ]:
132- set_params = {k : v for k , v in params .items () if v not in (None , "" , 0 )}
135+ ) -> Tuple [Dict [str , Any ], int ]:
136+ """The JSON object of a successful response and its status. Required parameters (the
137+ operation's own, without a default) must be set; optional ones at their protobuf
138+ default are left unset."""
139+ required = {
140+ name
141+ for name , p in inspect .signature (operation ).parameters .items ()
142+ if p .default is p .empty and p .kind in (p .POSITIONAL_OR_KEYWORD , p .KEYWORD_ONLY )
143+ }
144+ for name in required & params .keys ():
145+ if params [name ] in (None , "" ):
146+ raise ValueError (f"{ name } must not be empty" )
147+ set_params = {k : v for k , v in params .items () if k in required or v not in (None , "" , 0 )}
133148 resp = await operation (
134149 project_id = PROJECT , _headers = headers , _request_timeout = self .timeout , ** set_params
135150 )
136- body = await resp .read ()
151+ try :
152+ body = await resp .read ()
153+ finally :
154+ resp .release ()
137155 if not 200 <= resp .status < 300 :
138156 raise _server_error (body , resp .status )
139- data = json .loads (body ) if body else {}
140- return data if isinstance (data , dict ) else {}
157+ try :
158+ data = json .loads (body ) if body else {}
159+ except ValueError :
160+ data = None
161+ if not isinstance (data , dict ):
162+ raise _malformed ("response is not a JSON object" , body , resp .status )
163+ return data , resp .status
141164
142165
143- def _parse (data : Any , response_class : Type [M ]) -> M :
166+ def _parse (data : Any , response_class : Type [M ], status : int ) -> M :
144167 # Fields this SDK doesn't know yet are ignored.
145- return json_format .ParseDict (data or {}, response_class (), ignore_unknown_fields = True )
168+ try :
169+ return json_format .ParseDict (data or {}, response_class (), ignore_unknown_fields = True )
170+ except json_format .ParseError as e :
171+ raise ServerError (ServerErrorCode .MALFORMED , f"malformed response: { e } " , status = status )
172+
173+
174+ def _malformed (reason : str , body : bytes , status : int ) -> ServerError :
175+ snippet = body [:200 ].decode ("utf-8" , errors = "replace" )
176+ return ServerError (ServerErrorCode .MALFORMED , f"{ reason } : { snippet } " , status = status )
146177
147178
148179def _server_error (body : bytes , status : int ) -> ServerError :
@@ -162,7 +193,7 @@ def _server_error(body: bytes, status: int) -> ServerError:
162193 code = _STATUS_CODES .get (status ) or (
163194 ServerErrorCode .INTERNAL if status >= 500 else ServerErrorCode .UNKNOWN
164195 )
165- return ServerError (code , msg or text , status = status )
196+ return ServerError (code , msg or text or f"HTTP { status } " , status = status )
166197
167198
168199def to_json (msg : Message ) -> Dict [str , Any ]:
0 commit comments