Debian Codegraph @

gavo/svcs/common.py

raw ◀ ▶
1 Debian patch touch this file
1 """
2 Common functions and classes for services and cores.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 import re
12 from urllib import parse as urlparse
13
•14 from gavo import pkg_resources
15
16 from gavo import base
17 from gavo import utils
18 from gavo.formal import nevowc
19
20
21 class Error(base.ExecutiveAction):
22 def __init__(self, msg, rd=None, hint=None, htmlMessage=None):
23 self.rd = rd
24 self.msg = msg
25 self.hint = hint
26 if htmlMessage is not None:
27 self.htmlMessage = htmlMessage
28 base.ExecutiveAction.__init__(self, msg)
29
30
31 class BadRequest(Error):
32 """raised to generate an HTTP 400 response in DALI.
33 """
34 httpCode = 400
35
36
37 class BadMethod(Error):
38 """raised to generate an HTTP 405 response.
39 """
40 httpCode = 405
41
42 def __str__(self):
43 return "This resource cannot respond to the HTTP '%s' method"%self.msg
44
45
46 class UnknownURI(Error, base.NotFoundError):
47 """raised to generate an HTTP 404 response.
48 """
49 httpCode = 404
50
51 def __str__(self):
52 return Error.__str__(self)
53
54
55 class ForbiddenURI(Error):
56 """raised to generate an HTTP 403 response.
57 """
58 httpCode = 403
59
60
61 class RequestEntityTooLarge(Error):
62 """raised to generate an HTTP 413 response.
63 """
64 httpCode = 413
65
66 def __init__(self, *args, **kwargs):
67 if "hint" not in kwargs:
68 kwargs["hint"] = (
69 "If you receive this error using sync, try again"
70 " with async (the limits are generally more generous there). If you"
71 " receive this message with async, see if the upload can be"
72 " reduced by transmitting only columns absolutely necessary.")
73 Error.__init__(self, *args, **kwargs)
74
75
76 class Authenticate(Error):
77 """raised to initiate an authentication request.
78
79 Authenticates are optionally constructed with the realm the user
80 shall authenticate in. If you leave the realm out, the DC-wide default
81 will be used.
82 """
83 httpCode = 403
84
85 def __init__(self, realm=base.getConfig("web", "realm"), hint=None):
86 self.realm = realm
87 Error.__init__(self, "This is a request to authenticate against %s"%realm,
88 hint=hint)
89
90
91 class RedirectBase(Error):
92 def __init__(self, dest, hint=None):
93 if isinstance(dest, bytes):
94 dest = dest.decode("utf-8")
95
96 self.rawDest = dest
97 dest = str(dest)
98 if not urlparse.urlparse(dest).netloc:
99 dest = base.getConfig("web", "serverURL")+base.makeSitePath(dest)
100 self.dest = dest
101 Error.__init__(self, "This is supposed to redirect to %s"%dest,
102 hint=hint)
103
104
105 class WebRedirect(RedirectBase):
106 """raised to redirect a user agent to a different resource (HTTP 301).
107
108 WebRedirects are constructed with the destination URL that can be
109 relative (to webRoot) or absolute (starting with http).
110 """
111 httpCode = 301
112
113
114 class SeeOther(RedirectBase):
115 """raised to redirect a user agent to a different resource (HTTP 303).
116
117 SeeOthers are constructed with the destination URL that can be
118 relative (to webRoot) or absolute (starting with http).
119
120 They are essentially like WebRedirect, except they put out a 303
121 instead of a 301.
122 """
123 httpCode = 303
124
125
126 class Found(RedirectBase):
127 """raised to redirect a user agent to a different resource (HTTP 302).
128
129 Found instances are constructed with the destination URL that can be
130 relative (to webRoot) or absolute (starting with http).
131
132 They are essentially like WebRedirect, except they put out a 302
133 instead of a 301.
134 """
135 httpCode = 302
136
137
138 def parseServicePath(serviceParts):
139 """returns a tuple of resourceDescriptor, serviceName.
140
141 A service id consists of an inputsDir-relative path to a resource
142 descriptor, a slash, and the name of a service within this descriptor.
143
144 This function returns a tuple of inputsDir-relative path and service name.
145 It raises a gavo.Error if sid has an invalid format. The existence of
146 the resource or the service are not checked.
147 """
148 return "/".join(serviceParts[:-1]), serviceParts[-1]
149
150
151 class QueryMeta(dict):
152 """A class keeping information on the query environment.
153
154 It is constructed with a plain dictionary (there are alternative
155 constructors for t.w requests are below) mapping
156 certain keys (you'll currently have to figure out which from the
157 source) to values, mostly strings, except for the keys listed in
158 listKeys, which should be sequences of strings.
159
160 If you pass an empty dict, some sane defaults will be used. You
161 can get that "empty" query meta as common.emptyQueryMeta, but make
162 sure you don't mutate it.
163
164 QueryMetas constructed from request will have the user and password
165 items filled out.
166
167 If you're using formal, you should set the formal_data item
168 to the dictionary created by formal. This will let people use
169 the parsed parameters in templates.
170
171 You can do some amount of auth through queryMeta by using getAuthUser();
172 this may be an expensive operation, though, so only do it when you need
173 to, in particular only if user_pretend is nonempty. It's only available if
174 queryMeta was built from a request and simply hands through there.
175 """
176
177 # a set of keys that have sequences as values (needed for construction
178 # from t.w request.strargs)
179 listKeys = set(["_ADDITEM", "_DBOPTIONS_ORDER", "_SET"])
180
181 def __init__(self, initArgs=None, defaultLimit=None):
182 if initArgs is None:
183 initArgs = {}
184 self.ctxArgs = utils.CaseSemisensitiveDict(initArgs)
185 if defaultLimit is None:
186 self.defaultLimit = base.getConfig("db", "defaultLimit")
187 else:
188 self.defaultLimit = defaultLimit
189 self["formal_data"] = {}
190 self["user_pretend"] = None
191 self["accept"] = {}
192 self["inputTable"] = None
193 self._fillOutput(self.ctxArgs)
194 self._fillDbOptions(self.ctxArgs)
195 self._fillSet(self.ctxArgs)
196
197 def getAuthUser(self):
198 raise ValueError("I have not seen a request and hence do not"
199 " know about authenticated users.")
200
201 @classmethod
202 def fromRequest(cls, request, **kwargs):
203 """constructs a QueryMeta from a gavo.web.common.Request.
204
205 In addition to getting information from the arguments, this
206 also sets user and password.
207 """
208 args = {}
209 for key, value in request.strargs.items():
210 # defense against broken legacy code: listify if necessary
211 if not isinstance(value, list):
212 value = [value]
213
214 if key in cls.listKeys:
215 args[key] = value
216 else:
217 if value:
218 args[key] = value[0]
219 res = cls(args, **kwargs)
220
221 res.getAuthUser = request.getAuthUser
222 res["accept"] = utils.parseAccept(request.getHeader("accept"))
223 res["user_pretend"] = request.getUser()
224 res["accept"] = {}
225
226 # preserve the request string so svcs.Service can set the request meta
227 # item. The "<unrepresentable>" is when POSTs have non-GET-table
228 # items.
229 reqURI = request.asGETURI()
230 if reqURI!="<unrepresentable>":
231 res["requestURI"] = reqURI
232
233 return res
234
235 def _fillOutput(self, args):
236 """interprets RESPONSEFORMAT and _FORMAT, as well as _VERB/VERB
237
238 We will have no format key if neither is given, with RESPONSEFORMAT
239 taking precedence. Services must then inspect the current renderer's
240 defaultOutputFormat attribute.
241
242 verbosity will default to 20. _VERB gives verlevels directory,
243 VERB is SCS-compliant.
244
245 This also reads the legacy _TDENC and _VOTABLE_VERSION keys
246 that the ancient HTML format selector still produces. Let's move that
247 to using RESPONSEFORMAT one of these days.
248 """
249 if "RESPONSEFORMAT" in args:
250 self["format"] = args["RESPONSEFORMAT"]
251 elif "_FORMAT" in args:
252 self["format"] = args["_FORMAT"]
253
254 try:
255 # prefer fine-grained "verbosity" over _VERB or VERB
256 # Hack: malformed _VERBs result in None verbosity, which is taken to
257 # mean about "use fields of HTML". Absent _VERB or VERB, on the other
258 # hand, means VERB=2, i.e., a sane default
259 if "verbosity" in args:
260 self["verbosity"] = int(args["verbosity"])
261 elif "_VERB" in args: # internal verb parameter
262 self["verbosity"] = int(args["_VERB"])*10
263 elif "VERB" in args: # verb parameter for SCS and such
264 self["verbosity"] = int(args["VERB"])*10
265 else:
266 self["verbosity"] = 20
267 except ValueError:
268 self["verbosity"] = "HTML" # VERB given, but not an int.
269
270 self["tdEnc"] = base.getConfig("ivoa", "votDefaultEncoding")=="td"
271 if "_TDENC" in args:
272 try:
273 self["tdEnc"] = base.parseBooleanLiteral(args["_TDENC"])
274 except ValueError:
275 pass
276
277 try:
278 self["VOTableVersion"] = tuple(int(v) for v in
279 args["_VOTABLE_VERSION"].split("."))
280 except: # simple ignore malformed version specs
281 pass
282
283 self["additionalFields"] = args.get("_ADDITEM", [])
284
285 def _fillSet(self, args):
286 """interprets the output of a ColumnSet widget.
287 """
288 self["columnSet"] = None
289 if "_SET" in args:
290 self["columnSet"] = set(args["_SET"])
291
292 def _fillDbOptions(self, args):
293 self["dbSortKeys"] = [s.strip()
294 for s in args.get("_DBOPTIONS_ORDER", []) if s.strip()]
295
296 self["direction"] = {"ASC": "ASC", "DESC": "DESC"}[
297 args.get("_DBOPTIONS_DIR", "ASC")]
298
299 try:
300 self["dbLimit"] = int(args["MAXREC"])
301 except (ValueError, KeyError):
302 self["dbLimit"] = self.defaultLimit
303
304 try:
305 self["timeout"] = max(float(args["_TIMEOUT"]), 0.001)
306 except (ValueError, KeyError):
307 self["timeout"] = base.getConfig("web", "sqlTimeout")
308
309 def overrideDbOptions(self, sortKeys=None, limit=None, sortFallback=None,
310 direction=None):
311 if sortKeys is not None:
312 self["dbSortKeys"] = sortKeys
313 if not self["dbSortKeys"] and sortFallback is not None:
314 self["dbSortKeys"] = sortFallback.split(",")
315 if limit is not None:
316 self["dbLimit"] = int(limit)
317 if direction is not None:
318 self["direction"] = direction
319
320 def asSQL(self):
321 """returns the dbLimit and dbSortKey values as an SQL fragment.
322 """
323 frag, pars = [], {}
324 sortKeys = self["dbSortKeys"]
325 dbLimit = self["dbLimit"]
326 # TODO: Sorting needs a thorough redesign, presumably giving column instance
327 # as column keys. These could carry "default up" or "default down" in
328 # properties. Meanwhile, there should be a UI to let users decide on
329 # sort direction.
330 # Meanwhile, let's do an emergency hack.
331 if sortKeys:
332 # Ok, we need to do some emergency securing here. There should be
333 # pre-validation that we're actually seeing a column key, but
334 # just in case let's make sure we're seeing an SQL identifier.
335 # (We can't rely on dbapi's escaping since we're not talking values here)
336 frag.append("ORDER BY %s %s"%(",".join(
337 re.sub('[^A-Za-z0-9"_]+', "", key) for key in sortKeys),
338 self["direction"]))
339 if dbLimit:
340 frag.append("LIMIT %(_matchLimit)s")
341 pars["_matchLimit"] = int(dbLimit)+1
342 return " ".join(frag), pars
343
344
345 emptyQueryMeta = QueryMeta()
346
347
348 def getTemplatePath(key):
349 """see loadSystemTemplate.
350 """
351 userPath = base.getConfig("rootDir") / "web" / "templates" / key
352 if userPath.exists():
353 return userPath
354 else:
355 resPath = "resources/templates/"+key
356 if pkg_resources.resource_exists('gavo', resPath):
357 return pkg_resources.resource_filename('gavo', resPath)
358 else:
359 raise base.NotFoundError(key, "template", "system templates")
360
361
362 def loadSystemTemplate(key):
363 """returns a nevow template for system pages from key.
364
365 path is interpreted as relative to gavo_root/web/templates (first)
366 and package internal (last). If no template is found, None is
367 returned (this harmonizes with the fallback in CustomTemplateMixin).
368
369 Note that nevowc.XMLFile at this point ignores the doctype of the
370 template. For non-XHTML doctypes, set a gavo_useDoctype attribute
371 on the renderer.
372 """
373 try:
374 tp = getTemplatePath(key)
375 if tp is not None:
376 return nevowc.XMLFile(tp)
377 except IOError:
378 pass