Debian Codegraph @

gavo/votable/tapquery.py

raw
1 """
2 An interface to querying TAP servers (i.e., a TAP client).
3
4 This is deprecated. Use pyvo.dal.tap instead.
5 """
6
7 #c Copyright 2008-2025, the GAVO project <[email protected]>
8 #c
9 #c This program is free software, covered by the GNU GPL. See the
10 #c COPYING file in the source distribution.
11
12
13 import datetime
14 import io
15 import http.client
16 import socket
17 import time
18 import traceback
19 import urllib.request, urllib.parse, urllib.error
20 import urllib.parse
21 from email.message import Message
22 from email.mime.multipart import MIMEMultipart
23 from xml import sax
24
25 from gavo import utils
26 from gavo.votable import votparse
27 from gavo.votable.model import VOTable as V
28
29 from gavo.utils.dachstypes import (cast,
30 Any, BytesReadable, Callable, Dict, List, Mapping, Optional, Protocol, Set,
31 StrOrBytes, StrToStrMap, Tuple, Type, Union)
32
33
34 # Ward against typos
35 PENDING = "PENDING"
36 QUEUED = "QUEUED"
37 EXECUTING = "EXECUTING"
38 COMPLETED = "COMPLETED"
39 ERROR = "ERROR"
40 ABORTED = "ABORTED"
41 UNKNOWN = "UNKNOWN"
42
43
44 # override this as you see fit
45 USER_AGENT = "Python TAP library http://soft.g-vo.org/subpkgs"
46
47
48 debug = False
49
50
51 class Error(utils.Error):
52 """The base class for all TAP-related exceptions.
53 """
54
55
56 class ProtocolError(Error):
57 """is raised when the remote server violated the local assumptions.
58 """
59
60
61 class WrongStatus(ProtocolError):
62 """is raised when request detects the server returned an invalid
63 status.
64
65 These are constructed with the status returned (available as
66 foundStatus) data payload of the response (available as payload).
67 """
68 def __init__(self,
69 msg: str,
70 foundStatus: int,
71 payload: StrOrBytes,
72 hint: Optional[Any] = None) -> None:
73 ProtocolError.__init__(self, msg, hint)
74 self.args = (msg, foundStatus, payload, hint)
75 self.payload, self.foundStatus = payload, foundStatus
76
77
78 class RemoteError(Error):
79 """is raised when the remote size signals an error.
80
81 The content of the remote error document can be retrieved in the
82 remoteMessage attribute.
83 """
84 def __init__(self, remoteMessage: str):
85 self.remoteMessage = remoteMessage
86 Error.__init__(self,
87 "Remote: "+remoteMessage,
88 hint="This means that"
89 " something in your query was bad according to the server."
90 " Details may be available in the Exceptions' remoteMessage"
91 " attribute")
92 self.args = (remoteMessage,)
93
94 def __str__(self) -> str:
95 return self.remoteMessage
96
97
98 class RemoteAbort(Error):
99 """is raised by certain check functions when the remote side has aborted
100 the job.
101 """
102 def __init__(self):
103 Error.__init__(self, "Aborted")
104 self.args = []
105
106 def __str__(self) -> str:
107 return "The remote side has aborted the job"
108
109
110 class NetworkError(Error):
111 """is raised when a generic network error happens (can't connect,...)
112 """
113
114
115 class _HTTPResponseWithData(http.client.HTTPResponse):
116 """An augmented HTTP response with a patched-in data attribute.
117 """
118 data: bytes = b""
119
120
121 class _FormData(MIMEMultipart):
122 """is a container for multipart/form-data encoded messages.
123
124 This is usually used for file uploads.
125 """
126 def __init__(self):
127 MIMEMultipart.__init__(self, "form-data")
128 self.set_param("boundary", "========== bounda r y 930")
129 self.epilogue = ""
130
131 def addFile(self, paramName: str, fileName: str, data: bytes) -> None:
132 """attaches the contents of fileName under the http parameter name
133 paramName.
134 """
135 msg = Message()
136 msg.set_type("application/octet-stream")
137 msg["Content-Disposition"] = "form-data"
138 msg.set_param("name", paramName, "Content-Disposition")
139 msg.set_param("filename", fileName, "Content-Disposition")
140 msg.set_payload(data)
141 self.attach(msg)
142
143 def addParam(self, paramName: str, paramVal: bytes) -> None:
144 """adds a form parameter paramName with the (string) value paramVal
145 """
146 msg = Message()
147 msg["Content-Disposition"] = "form-data"
148 msg.set_param("name", paramName, "Content-Disposition")
149 msg.set_payload(paramVal)
150 self.attach(msg)
151
152 def forHTTPUpload(self) -> str:
153 """returns a string serialisation of this message suitable for HTTP
154 upload.
155
156 This is as_string, except we're cutting off the header (which is
157 part of the HTTP header for us), and we are changing the line separator
158 to crlf.
159 """
160 data = self.as_string().split("\n\n", 1)[-1]
161 data = data.replace("\n", "\r\n")
162 return data
163
164 @classmethod
165 def fromDict(cls, dict: Mapping[str, StrOrBytes]) -> "_FormData":
166 self = cls()
167 for key, value in dict.items():
168 self.addParam(key, utils.bytify(value))
169 return self
170
171
172 def _getErrorInfo(votString: StrOrBytes) -> str:
173 """returns the message from a TAP error VOTable.
174
175 if votString is not a TAP error VOTable, it is returned verbatim
176 (decoded as UTF-8)
177
178 TODO: For large responses, this may take a while. It's probably
179 not worth it in such cases. Or at all. Maybe we should hunt
180 for the INFO somewhere else?
181 """
182 try:
183 for el in votparse.parseBytes(utils.bytify(votString), watchset={V.INFO}):
184 if isinstance(el, V.INFO):
185 if el.name=="QUERY_STATUS" and el.value=="ERROR":
186 return el.text_
187 else:
188 # it's data, which we want to skip quickly
189 for _ in el: pass
190 except Exception:
191 # votString's not a suitable VOTable, fall through to return votString
192 pass
193 return utils.debytify(votString)
194
195
196 class _JobresParser(Protocol):
197 """an object that takes one of our request results and builds python
198 values from its payload.
199
200 In practical terms, this is either a _FlatParser (for which all this
201 is a bit too much effort) or a StartEndParser if we have to deal
202 with XML responses.
203 """
204 def getResult(self) -> Any:
205 pass
206
207 def parseString(self, data: StrOrBytes) -> Any:
208 # the return value is ignored here
209 pass
210
211
212 class _FlatParser:
213 """a "parser" for use within _parseWith.
214 """
215 def __init__(self, parseFunc: Callable[[StrOrBytes], Any]) -> None:
216 self.parseFunc = parseFunc
217
218 def parseString(self, data: StrOrBytes) -> None:
219 self.result = self.parseFunc(data)
220
221 def getResult(self):
222 return self.result
223
224
225 def _parseWith(parser: "_JobresParser", data: StrOrBytes):
226 """uses the utils.StartEndParser-compatible parser to parse the string data.
227 """
228 try:
229 parser.parseString(data)
230 return parser.getResult()
231 except (ValueError, IndexError, sax.SAXParseException):
232 if debug:
233 traceback.print_exc()
234 with open("server_response", "wb") as f:
235 f.write(utils.bytify(data))
236 raise ProtocolError("Malformed response document.", hint=
237 "If debug was enabled, you will find the server response in"
238 " the file server_response.")
239
240
241 class _PhaseParser(utils.StartEndHandler):
242 """A parser accepting both plain text and XML replies.
243
244 Of course, the XML replies are against the standard, but "be lenient
245 in what you accept", and I used to be out there.
246 """
247 result: Optional[str] = ""
248
249 def _end_phase(self, name: str, attrs: StrToStrMap, content: str) -> None:
250 self.result = content
251
252 def parseString(self, data: StrOrBytes) -> "_PhaseParser":
253 if utils.bytify(data).strip().startswith(b"<"): # XML :-)
254 utils.StartEndHandler.parseString(self, data)
255 else:
256 self.result = utils.debytify(data.strip())
257 return self
258
259 def getResult(self) -> Optional[str]:
260 return self.result
261
262
263 class _QuoteParser(utils.StartEndHandler):
264 quote: Optional[datetime.datetime] = None
265
266 def parseDate(self, arg: StrOrBytes) -> Optional[datetime.datetime]:
267 literal = utils.debytify(arg)
268 val = None
269 if literal and literal!="NULL":
270 val = utils.parseISODT(literal)
271 return val
272
273 def _end_quote(self, name: str, attrs: StrToStrMap, content: str) -> None:
274 self.quote = self.parseDate(content.strip())
275
276 def parseString(self, data: StrOrBytes) -> utils.StartEndHandler:
277 data = data.strip()
278 if utils.bytify(data).startswith(b"<"): # XML :-)
279 utils.StartEndHandler.parseString(self, data)
280 else:
281 self.quote = self.parseDate(data)
282 return self
283
284 def getResult(self) -> Optional[datetime.datetime]:
285 return self.quote
286
287
288 class _CaselessDictionary(dict):
289 """A dictionary that only has lower-case keys but treats keys in any
290 capitalization as equivalent.
291 """
292 def __contains__(self, key: object) -> bool:
293 if isinstance(key, str):
294 key = key.lower()
295 return dict.__contains__(self, key)
296
297 def __getitem__(self, key: str) -> bool:
298 return dict.__getitem__(self, key.lower())
299
300 def __setitem__(self, key: str, value: Any) -> None:
301 dict.__setitem__(self, key.lower(), value)
302
303 def __delitem__(self, key: str) -> None:
304 dict.__delitem__(self, key.lower())
305
306
307 class _ParametersParser(utils.StartEndHandler):
308 def _initialize(self) -> None:
309 self.parameters = _CaselessDictionary()
310
311 def _end_parameter(self, name: str, attrs: StrToStrMap, content: str
312 ) -> None:
313 self.parameters[attrs["id"]] = content
314
315 def getResult(self) -> _CaselessDictionary:
316 return self.parameters
317
318
319 class _ResultsParser(utils.StartEndHandler):
320 def _initialize(self) -> None:
321 self.results: List[UWSResult] = []
322
323 def _end_result(self, name: str, attrs: StrToStrMap, content: str
324 ) -> None:
325 attrs = self.getAttrsAsDict(attrs)
326 self.results.append(UWSResult(attrs["href"],
327 attrs.get("id"), attrs.get("type", "simple")))
328
329 def getResult(self) -> List["UWSResult"]:
330 return self.results
331
332
333 class _InfoParser(_ParametersParser, _ResultsParser):
334 def _initialize(self) -> None:
335 self.info: Dict[str, Any] = {}
336 _ParametersParser._initialize(self)
337 _ResultsParser._initialize(self)
338
339 def _end_jobId(self, name: str, attrs: StrToStrMap, content: str
340 ) -> None:
341 self.info[name] = content
342
343 _end_phase = _end_jobId
344
345 def _end_executionDuration(self,
346 name: str, attrs: StrToStrMap, content: str) -> None:
347 self.info[name] = float(content)
348
349 def _end_destruction(self,
350 name: str, attrs: StrToStrMap, content: str) -> None:
351 self.info[name] = utils.parseISODT(content)
352
353 def _end_job(self,
354 name: str, attrs: StrToStrMap, content: str) -> None:
355 self.info["results"] = self.results
356 self.info["parameters"] = self.parameters
357
358 def getResult(self) -> Dict[str, Any]: # type: ignore # inheritance is a bit wonky here
359 return self.info
360
361
362 class _AvailabilityParser(utils.StartEndHandler):
363 # Let's drop this; availability was a bad idea.
364 available: Optional[bool] = None
365
366 def _end_available(self, name: str, attrs: StrToStrMap, content: str
367 ) -> None:
368 content = content.strip()
369 if content=="true":
370 self.available = True
371 elif content=="false":
372 self.available = False
373
374 def getResult(self) -> Optional[bool]:
375 return self.available
376
377
378 def _pruneAttrNS(attrs: StrToStrMap) -> StrToStrMap:
379 return dict((k.split(":")[-1], v) for k,v in list(attrs.items()))
380
381
382 class _CapabilitiesParser(utils.StartEndHandler):
383 # VOSI; each capability is a dict with at least a key interfaces.
384 # each interface is a dict with key type (namespace prefix not expanded;
385 # change that?), accessURL, and use.
386 def __init__(self) -> None:
387 utils.StartEndHandler.__init__(self)
388 self.capabilities: List[Dict[str, Any]] = []
389 self.curInterface: Optional[Dict[str, Any]] = None
390
391 def _start_capability(self, name: str, attrs: StrToStrMap) -> None:
392 self.curCap: Optional[Dict[str, Any]] = {"interfaces": []}
393 self.curCap["standardID"] = attrs.get("standardID")
394
395 def _end_capability(self, name: str, attrs: StrToStrMap, content: str
396 ) -> None:
397 if self.curCap is not None:
398 self.capabilities.append(self.curCap)
399 self.curCap = None
400
401 def _start_interface(self, name: str, attrs: StrToStrMap):
402 attrs = _pruneAttrNS(attrs)
403 self.curInterface = {
404 "type": attrs["type"],
405 "role": attrs.get("role")}
406
407 def _end_interface(self,name: str, attrs: StrToStrMap, content: str
408 ) -> None:
409 if self.curInterface is not None and self.curCap is not None:
410 self.curCap["interfaces"].append(self.curInterface)
411 self.curInterface = None
412
413 def _end_accessURL(self, name: str, attrs: StrToStrMap, content: str
414 ) -> None:
415 if self.curInterface is not None:
416 self.curInterface["accessURL"] = content.strip()
417 self.curInterface["use"] = attrs.get("use")
418
419 def getResult(self) -> List[Dict[str, Any]]:
420 return self.capabilities
421
422
423 class _TablesParser(utils.StartEndHandler):
424 def __init__(self) -> None:
425 utils.StartEndHandler.__init__(self)
426 self.tables: List[V.TABLE] = []
427 self.curCol: Optional[V.FIELD] = None
428
429 def _start_table(self, name: str, attrs: StrToStrMap) -> None:
430 self.tables.append(V.TABLE())
431
432 def _start_column(self, name: str, attrs: StrToStrMap) -> None:
433 self.curCol = V.FIELD()
434
435 def _end_column(self, name: str, attrs: StrToStrMap, content: str
436 ) -> None:
437 self.tables[-1][self.curCol]
438 self.curCol = None
439
440 def _end_description(self,
441 attname: str, attrs: StrToStrMap, content: str) -> None:
442 if self.getParentTag()=="table":
443 destObj: V._VOTElement = self.tables[-1]
444 elif self.getParentTag()=="column" and self.curCol is not None:
445 destObj = self.curCol
446 else:
447 # name/desc of something else -- ignore
448 return
449 destObj[V.DESCRIPTION[content]]
450
451 def _endColOrTableAttr(self,
452 attname: str, attrs: StrToStrMap, content: str) -> None:
453 if self.getParentTag()=="table":
454 destObj: V._VOTElement = self.tables[-1]
455 elif self.getParentTag()=="column" and self.curCol is not None:
456 destObj = self.curCol
457 else:
458 # name/desc of something else -- ignore
459 return
460 destObj(**{str(attname): content.strip()})
461
462 _end_name = _endColOrTableAttr
463
464 def _endColAttr(self, attName: str, attrs: StrToStrMap, content: str
465 ) -> None:
466 if self.curCol is not None:
467 self.curCol(**{str(attName): content.strip()})
468
469 _end_unit = _end_ucd = _endColAttr
470
471 def _end_dataType(self, attname: str, attrs: StrToStrMap, content: str
472 ) -> None:
473 if self.curCol is not None:
474 self.curCol(datatype=content.strip())
475 if "arraysize" in attrs:
476 self.curCol(arraysize=attrs["arraysize"])
477
478 def getResult(self) -> List[V.TABLE]:
479 return self.tables
480
481
482 class UWSResult:
483 """a container type for a result returned by an UWS service.
484
485 It exposes id, href, and type attributes.
486 """
487 def __init__(self,
488 href: str,
489 id: Optional[str] = None,
490 type: Optional[str] = None) -> None:
491 self.href, self.id, self.type = href, id, type
492
493
494 class LocalResult:
495 def __init__(self, data: bytes, id: str, type: str) -> None:
496 self.data, self.id, self.type = data, id, type
497
498
499 def _canUseFormEncoding(params: Mapping[str, Any]) -> bool:
500 """returns true if userParams can be transmitted in a
501 x-www-form-urlencoded payload.
502 """
503 for val in list(params.values()):
504 if not isinstance(val, str):
505 return False
506 return True
507
508 ACCEPTED_REDIRECTS = {301, 302, 303, 307}
509
510
511 def request(
512 scheme: StrOrBytes,
513 host: StrOrBytes,
514 path: StrOrBytes,
515 data: Mapping[str, StrOrBytes] | str = "",
516 customHeaders: StrToStrMap = {},
517 method: str = "GET",
518 expectedStatus: Optional[int] = None,
519 followRedirects: int = 0,
520 setResponse: Optional[Callable[[bytes], None]] = None,
521 timeout: Optional[float] = None) -> _HTTPResponseWithData:
522 """returns a HTTPResponse object for an HTTP request to path on host.
523
524 This function builds a new connection for every request.
525
526 On the returned object, you cannot use the read() method. Instead
527 any data returned by the server is available in the data attribute.
528
529 data usually is a byte string, but you can also pass a dictionary
530 which then will be serialized using _FormData above.
531
532 You can set followRedirects to a positive integer. This means that the
533 303 "See other" codes that many UWS action generate will be followed
534 and the document at the other end will be obtained. DaCHS will
535 follow as many redirects.
536
537 In setResponse, you can pass in a callable that is called with the
538 server response body as soon as it is in. This is for when you want
539 to store the response even if request raises an error later on
540 (i.e., for sync querying).
541 """
542 if scheme=="http":
543 connClass: Union[
544 Type[http.client.HTTPConnection],
545 Type[http.client.HTTPSConnection]]= http.client.HTTPConnection
546 elif scheme=="https":
547 connClass = http.client.HTTPSConnection
548 else:
549 assert False
550
551 headers = {"connection": "close",
552 "user-agent": USER_AGENT}
553
554 if not isinstance(data, str):
555 if _canUseFormEncoding(data):
556 data = urllib.parse.urlencode(data)
557 headers["Content-Type"] = "application/x-www-form-urlencoded"
558
559 else:
560 form = _FormData.fromDict(data)
561 data = form.forHTTPUpload()
562 headers["Content-Type"] = form.get_content_type()+'; boundary="%s"'%(
563 form.get_boundary())
564
565 headers["Content-Length"] = str(len(data))
566 headers.update(customHeaders)
567
568 try:
569 conn = connClass(utils.debytify(host), timeout=timeout)
570 conn.request(utils.debytify(method), utils.debytify(path), data, headers)
571 except (socket.error, http.client.error) as ex:
572 raise NetworkError("Problem connecting to {} ({})".format(
573 utils.debytify(host), ex))
574
575 resp: _HTTPResponseWithData = cast(_HTTPResponseWithData, conn.getresponse())
576 resp.data = resp.read()
577 if setResponse is not None:
578 setResponse(resp.data)
579 conn.close()
580
581 if followRedirects and resp.status in ACCEPTED_REDIRECTS:
582 parts = urllib.parse.urlparse(resp.getheader("location"))
583 return request(parts.scheme, parts.netloc, parts.path,
584 method="GET", expectedStatus=expectedStatus,
585 followRedirects=followRedirects-1)
586
587 if expectedStatus is not None:
588 if resp.status!=expectedStatus:
589 raise WrongStatus("Expected status %s, got status %s"%(
590 expectedStatus, resp.status), resp.status, resp.data)
591 return resp
592
593
594 def _makeAtomicValueGetter(methodPath: str, parser: _FlatParser
595 ) -> Callable[[_FlatParser], Any]:
596 # This is for building ADQLTAPJob's properties (phase, etc.)
597 def getter(self):
598 destURL = self.jobPath+methodPath
599 response = request(self.destScheme, self.destHost, destURL,
600 expectedStatus=200)
601 return _parseWith(parser, response.data)
602 return getter
603
604
605 def _makeAtomicValueSetter(
606 methodPath: str,
607 serializer: Callable[[Any], str],
608 parameterName: str) -> Callable[["ADQLTAPJob", Any], None]:
609 # This is for building ADQLTAPJob's properties (phase, etc.)
610 def setter(self: "ADQLTAPJob", value: Any) -> None:
611 destURL = self.jobPath+methodPath
612 request(self.destScheme, self.destHost, destURL,
613 {parameterName: serializer(value)}, method="POST",
614 expectedStatus=303)
615 return setter
616
617
618 class _WithEndpoint:
619 """A helper class for classes constructed with an ADQL endpoint.
620 """
621 def _defineEndpoint(self, endpointURL: str) -> None:
622 self.endpointURL = endpointURL.rstrip("/")
623 parts = urllib.parse.urlsplit(self.endpointURL)
624 self.destScheme = parts.scheme
625 self.destHost = cast(str, parts.hostname)
626 if parts.port:
627 self.destHost = "%s:%s"%(self.destHost, parts.port)
628 self.destPath = parts.path
629 if self.destPath.endswith("/"):
630 self.destPath = self.destPath[:-1]
631
632
633
634 class ADQLTAPJob(_WithEndpoint):
635 """A facade for an ADQL-based async TAP job.
636
637 Construct it with the URL of the async endpoint and a query.
638
639 Alternatively, you can give the endpoint URL and a jobId as a
640 keyword parameter. This only makes sense if the service has
641 handed out the jobId before (e.g., when a different program takes
642 up handling of a job started before).
643
644 See :dachsdoc:`adql.html` for details.
645 """
646 def __init__(self,
647 endpointURL: str,
648 query: Optional[str] = None,
649 jobId: Optional[str] = None,
650 lang: str = "ADQL",
651 userParams: StrToStrMap = {},
652 timeout: Optional[int] = None) -> None:
653 self._defineEndpoint(endpointURL)
654 self.timeout = timeout
655 self.destPath = utils.ensureOneSlash(self.destPath)+"async"
656 if query is not None:
657 self.jobId: Optional[str] = None
658 self.jobPath: str = ""
659 self._createJob(query, lang, userParams)
660 elif jobId is not None:
661 self.jobId = jobId
662 else:
663 raise Error("Must construct ADQLTAPJob with at least query or jobId")
664 self._computeJobPath()
665
666 def _computeJobPath(self) -> None:
667 self.jobPath = "%s/%s"%(self.destPath, self.jobId)
668
669 def _createJob(self, query: str, lang: str, userParams: StrToStrMap
670 ) -> None:
671 params = {
672 "REQUEST": "doQuery",
673 "LANG": lang,
674 "QUERY": query}
675 for k,v in userParams.items():
676 params[k] = str(v)
677 response = request(self.destScheme, self.destHost, self.destPath, params,
678 method="POST", expectedStatus=303, timeout=self.timeout)
679 # The last part of headers[location] now contains the job id
680 try:
681 self.jobId = urllib.parse.urlsplit(
682 response.getheader("location", "")).path.split("/")[-1]
683 except ValueError:
684 raise utils.logOldExc(
685 ProtocolError("Job creation returned invalid job id"))
686
687 def delete(self, usePOST: bool = False) -> None:
688 """removes the job on the remote side.
689
690 usePOST=True can be used for servers that do not support the DELETE
691 HTTP method (a.k.a. "are broken").
692 """
693 if self.jobPath is not None:
694 if usePOST:
695 request(self.destScheme, self.destHost, self.jobPath, method="POST",
696 data={"ACTION": "DELETE"}, expectedStatus=303,
697 timeout=self.timeout)
698 else:
699 request(self.destScheme, self.destHost, self.jobPath, method="DELETE",
700 expectedStatus=303, timeout=self.timeout)
701
702 def start(self) -> None:
703 """asks the remote side to start the job.
704 """
705 request(self.destScheme, self.destHost, self.jobPath+"/phase",
706 {"PHASE": "RUN"}, method="POST", expectedStatus=303,
707 timeout=self.timeout)
708
709 def abort(self) -> None:
710 """asks the remote side to abort the job.
711 """
712 request(self.destScheme, self.destHost, self.jobPath+"/phase",
713 {"PHASE": "ABORT"}, method="POST", expectedStatus=303,
714 timeout=self.timeout)
715
716 def raiseIfError(self) -> None:
717 """raises an appropriate error message if job has thrown an error or
718 has been aborted.
719 """
720 phase = self.phase
721 if phase==ERROR:
722 raise RemoteError(self.getErrorFromServer())
723 elif phase==ABORTED:
724 raise RemoteAbort()
725
726 def waitForPhases(self,
727 phases: Set[str],
728 pollInterval: float = 1,
729 increment: float = 1.189207115002721,
730 giveUpAfter: Optional[int] = None) -> None:
731 """waits for the job's phase to become one of the set phases.
732
733 This method polls. Initially, it does increases poll times
734 exponentially with increment until it queries every two minutes.
735
736 The magic number in increment is 2**(1/4.).
737
738 giveUpAfter, if given, is the number of iterations this method will
739 do. If none of the desired phases have been found until then,
740 raise a ProtocolError.
741 """
742 attempts = 0
743 while True:
744 curPhase = self.phase
745 if curPhase in phases:
746 break
747 time.sleep(pollInterval)
748 pollInterval = min(120, pollInterval*increment)
749 attempts += 1
750 if giveUpAfter:
751 if attempts>giveUpAfter:
752 raise ProtocolError("None of the states in %s were reached"
753 " in time."%repr(phases),
754 hint="After %d attempts, phase was %s"%(attempts, curPhase))
755
756 def run(self, pollInterval: float = 1) -> None:
757 """runs the job and waits until it has finished.
758
759 The function raises an exception with an error message gleaned from the
760 server.
761 """
762 self.start()
763 self.waitForPhases(set([COMPLETED, ABORTED, ERROR]))
764 self.raiseIfError()
765
766 executionDuration = property(
767 _makeAtomicValueGetter("/executionduration", _FlatParser(float)),
768 _makeAtomicValueSetter("/executionduration", str, "EXECUTIONDURATION"))
769
770 destruction = property(
771 _makeAtomicValueGetter("/destruction", _FlatParser(
772 lambda data: utils.parseISODT(utils.debytify(data)))),
773 _makeAtomicValueSetter("/destruction",
774 lambda dt: dt.strftime("%Y-%m-%dT%H:%M:%S.000"), "DESTRUCTION"))
775
776 def makeJobURL(self, jobPath: str) -> str:
777 return self.endpointURL+"/async/%s%s"%(self.jobId, jobPath)
778
779 def _queryJobResource(self, path: str, parser: _JobresParser) -> Any:
780 # a helper for phase, quote, etc.
781 response = request(self.destScheme, self.destHost, self.jobPath+path,
782 expectedStatus=200, timeout=self.timeout)
783 return _parseWith(parser, response.data)
784
785 @property
786 def info(self) -> Dict[str, Any]:
787 """returns a dictionary of much job-related information.
788 """
789 return self._queryJobResource("", _InfoParser())
790
791 @property
792 def phase(self) -> str:
793 """returns the phase the job is in according to the server.
794 """
795 return self._queryJobResource("/phase", _PhaseParser())
796
797 @property
798 def quote(self) -> datetime.datetime:
799 """returns the estimate the server gives for the run time of the job.
800 """
801 return self._queryJobResource("/quote", _QuoteParser())
802
803 @property
804 def owner(self) -> str:
805 """returns the owner of the job.
806 """
807 return self._queryJobResource("/owner",
808 _FlatParser(lambda data: utils.debytify(data)))
809
810 @property
811 def parameters(self) -> _CaselessDictionary:
812 """returns a dictionary mapping passed parameters to server-provided
813 string representations.
814
815 To set a parameter, use the setParameter function. Changing the
816 dictionary returned here will have no effect.
817 """
818 return self._queryJobResource("/parameters", _ParametersParser())
819
820 @property
821 def allResults(self) -> List[UWSResult]:
822 """returns a list of UWSResult instances.
823 """
824 return self._queryJobResource("/results", _ResultsParser())
825
826 def getResultURL(self, simple: bool = True) -> str:
827 """returns the URL of the ADQL result table.
828 """
829 if simple:
830 return self.makeJobURL("/results/result")
831 else:
832 return self.allResults[0].href
833
834 def openResult(self, simple: bool = True
835 ) -> str:
836 """returns a file-like object you can read the default TAP result off.
837
838 To have the embedded VOTable returned, say
839 votable.load(job.openResult()).
840
841 If you pass simple=False, the URL will be taken from the
842 service's result list (the first one given there). Otherwise (the
843 default), results/result is used.
844 """
845 return urllib.request.urlopen(self.getResultURL())
846
847 def setParameter(self, key: str, value: str) -> None:
848 request(self.destScheme, self.destHost, self.jobPath+"/parameters",
849 data={key: value}, method="POST", expectedStatus=303,
850 timeout=self.timeout)
851
852 def getErrorFromServer(self) -> str:
853 """returns the error message the server gives, verbatim.
854 """
855 data = request(self.destScheme, self.destHost, self.jobPath+"/error",
856 expectedStatus=200, followRedirects=True,
857 timeout=self.timeout).data
858 return _getErrorInfo(data)
859
860 def addUpload(self, name: str, data: bytes | BytesReadable) -> None:
861 """adds uploaded tables, either from a file or as a remote URL.
862
863 You should not try to change UPLOAD yourself (e.g., using setParameter).
864
865 Data is either a string (i.e. a URI) or a file-like object (an upload).
866 """
867 uploadFragments = []
868 form = _FormData()
869 if isinstance(data, str): # a URI
870 assert ',' not in data
871 assert ';' not in data
872 uploadFragments.append("%s,%s"%(name, data))
873
874 else: # Inline upload, data is a file
875 uploadKey = utils.intToFunnyWord(id(data))
876 form.addFile(uploadKey, uploadKey, cast(BytesReadable, data).read())
877 uploadFragments.append("%s,param:%s"%(name, uploadKey))
878
879 form.addParam("UPLOAD", utils.bytify(";".join(uploadFragments)))
880 request(self.destScheme, self.destHost, self.jobPath+"/parameters",
881 method="POST",
882 data=form.forHTTPUpload(), expectedStatus=303,
883 customHeaders={"content-type":
884 form.get_content_type()+'; boundary="%s"'%(form.get_boundary())})
885
886
887 class ADQLSyncJob(_WithEndpoint):
888 """A facade for a synchronous TAP Job.
889
890 This really is just a very glorified urllib.urlopen. Maybe some
891 superficial parallels to ADQLTAPJob are useful.
892
893 You can construct it, add uploads, and then start or run the thing.
894 Methods that make no sense at all for sync jobs ("phase") silently
895 return some more or less sensible fakes.
896 """
897 def __init__(self,
898 endpointURL: str,
899 query: Optional[str] = None,
900 jobId: Optional[str] = None,
901 lang: str = "ADQL",
902 userParams: Dict[str, str] = {},
903 timeout: Optional[float] = None) -> None:
904 self._defineEndpoint(endpointURL)
905 self.query, self.lang = query, lang
906 self.userParams = userParams.copy()
907 self.result: Optional[LocalResult] = None
908 self.uploads: List[Tuple[str, str, bytes]] = []
909 self._errorFromServer: Optional[str] = None
910 self.timeout = timeout
911
912 def postToService(self, params: Dict[str, StrOrBytes]
913 ) -> _HTTPResponseWithData:
914 return request(self.destScheme, self.destHost, self.destPath+"/sync",
915 params,
916 method="POST", followRedirects=5, expectedStatus=200,
917 setResponse=self._setErrorFromServer, timeout=self.timeout)
918
919 def delete(self, usePOST: bool = False) -> None:
920 # Nothing to delete
921 pass
922
923 def abort(self) -> None:
924 """does nothing.
925
926 You could argue that this could come from a different thread and we
927 could try to interrupt the ongoing request. Well, if you want it,
928 try it yourself or ask the author.
929 """
930
931 def raiseIfError(self) -> None:
932 if self._errorFromServer is not None:
933 raise Error(self._errorFromServer)
934
935 def waitForPhases(self,
936 phases: Set[str],
937 pollInterval: float = 1,
938 increment: float = 1.189207115002721,
939 giveUpAfter: Optional[int] = None) -> None:
940 # you could argue that sync jobs are in no phase, but I'd say
941 # they are in all of them at the same time:
942 return
943
944 def _setErrorFromServer(self, data: StrOrBytes) -> None:
945 # this is a somewhat convolved way to get server error messages
946 # out of request even when it later errors out. See the
947 # except construct around the postToService call in start()
948 #
949 # Also, try to interpret what's coming back as a VOTable with an
950 # error message; _getErrorInfo is robust against other junk.
951 self._errorFromServer = _getErrorInfo(data)
952
953 def start(self) -> "ADQLSyncJob":
954 if self.query is None:
955 raise NotImplementedError("No query?")
956
957 params: Dict[str, StrOrBytes] = {
958 "REQUEST": "doQuery",
959 "LANG": self.lang,
960 "QUERY": self.query}
961 params.update(self.userParams)
962 if self.uploads:
963 upFrags = []
964 for name, key, data in self.uploads:
965 upFrags.append("%s,param:%s"%(name, key))
966 params[key] = data
967 params["UPLOAD"] = ";".join(upFrags)
968
969 params = dict((k, str(v)) for k,v in params.items())
970
971 try:
972 resp = self.postToService(params)
973 self.result = LocalResult(
974 resp.data, "TAPResult", cast(str, resp.getheader("Content-Type")))
975 except Exception as msg:
976 # do not clear _errorFromServer; but if it's empty, make up one
977 # from our exception
978 if not self._errorFromServer:
979 self._errorFromServer = str(msg)
980 raise
981 else:
982 # all went well, clear error indicator
983 self._errorFromServer = None
984 return self
985
986 def run(self, pollInterval: Optional[float] = None):
987 return self.start()
988
989 @property
990 def info(self) -> StrToStrMap:
991 return {}
992
993 @property
994 def phase(self) -> None:
995 return None
996
997 @property
998 def quote(self) -> None:
999 return None
1000
1001 @property
1002 def owner(self) -> None:
1003 return None
1004
1005 @property
1006 def parameters(self) -> StrToStrMap:
1007 return self.userParams
1008
1009 @property
1010 def allResults(self) -> List[LocalResult]:
1011 if self.result is None:
1012 return []
1013 else:
1014 return [self.result]
1015
1016 def openResult(self, simple: bool = True) -> io.BytesIO:
1017 if self.result is None:
1018 raise Error("No result in so far")
1019 return io.BytesIO(self.result.data)
1020
1021 def setParameter(self, key: str, value: Any) -> None:
1022 self.userParams[key] = value
1023
1024 def getErrorFromServer(self) -> Optional[str]:
1025 return self._errorFromServer
1026
1027 def addUpload(self, name: str, data: bytes) -> None:
1028 if hasattr(data, "read"):
1029 data = data.read()
1030 if not isinstance(data, bytes):
1031 raise NotImplementedError("Upload source must be file or bytes")
1032 key = utils.intToFunnyWord(id(data))
1033 self.uploads.append((name, key, data))
1034
1035
1036 class ADQLEndpoint(_WithEndpoint):
1037 """A facade for an ADQL endpoint.
1038
1039 This is only needed for inspecting server metadata (i.e., in general
1040 only for rather fancy applications).
1041 """
1042 def __init__(self, endpointURL: str) -> None:
1043 self._defineEndpoint(endpointURL)
1044
1045 def createJob(self,
1046 query: str,
1047 lang: str = "ADQL-2.0",
1048 userParams: StrToStrMap = {}):
1049 return ADQLTAPJob(
1050 self.endpointURL, query, lang=lang, userParams=userParams)
1051
1052 @property
1053 def available(self) -> Optional[bool]:
1054 """returns True, False, or None (undecidable).
1055
1056 None is returned when /availability gives a 404 (which is legal)
1057 or the returned document doesn't parse.
1058 """
1059 try:
1060 response = request(self.destScheme, self.destHost,
1061 self.destPath+"/availability", expectedStatus=200)
1062 res = _parseWith(_AvailabilityParser(), response.data)
1063 except WrongStatus:
1064 res = None
1065 return res
1066
1067 @property
1068 def capabilities(self) -> List[StrToStrMap]:
1069 """returns a dictionary containing some meta info on the remote service.
1070
1071 Keys to look for include title, identifier, contact (the mail address),
1072 and referenceURL.
1073
1074 If the remote server doesn't return capabilities as expected, an
1075 empty dict is returned.
1076 """
1077 return _parseWith(_CapabilitiesParser(),
1078 request(self.destScheme, self.destHost,
1079 self.destPath+"/capabilities").data)
1080
1081 @property
1082 def tables(self) -> List[V.TABLE]:
1083 """returns a sequence of table definitions for the tables accessible
1084 through this service.
1085
1086 The table definitions come as gavo.votable.Table instances.
1087 """
1088 return _parseWith(_TablesParser(),
1089 request(self.destScheme, self.destHost, self.destPath+"/tables").data)