Debian Codegraph @

gavo/registry/oaiinter.py

raw
1 """
2 The standard OAI interface.
3
4 In this module the core handling the OAI requests and the top-level handlers
5 for the verbs are defined.
6
7 The top-level handlers are all called run_<verb> -- any such function
8 is web-callable.
9 """
10
11 #c Copyright 2008-2025, the GAVO project <[email protected]>
12 #c
13 #c This program is free software, covered by the GNU GPL. See the
14 #c COPYING file in the source distribution.
15
16
17 import datetime
18 import time
19 import urllib.parse as urlparse
20
21 from gavo import base
22 from gavo import svcs
23 from gavo import utils
24 from gavo.registry import builders
25 from gavo.registry import common
26 from gavo.registry import identifiers
27 from gavo.registry.model import OAI
28
29 from gavo.registry.common import ( #noflake: exported names
30 OAIError, BadArgument, BadResumptionToken, BadVerb,
31 CannotDisseminateFormat, IdDoesNotExist, NoMetadataFormats,
32 NoSetHierarchy, NoRecordsMatch)
33
34
35 ########################### Generic Processing of PMH requests
36
37 # a mapping of OAI verbs to optional and required argument names
38 _ARGUMENTS = {
39 "GetRecord": (["identifier", "metadataPrefix"], []),
40 "ListRecords": (["metadataPrefix"],
41 ["from", "until", "set", "resumptionToken"]),
42 "ListIdentifiers": (["metadataPrefix"],
43 ["from", "until", "set", "resumptionToken"]),
44 "ListSets": ([], []),
45 "Identify": ([], []),
46 "ListMetadataFormats": ([], ["identifier"]),}
47
48
49 def runPMH(pars, builders):
50 """runs the OAI-PMH handling function.
51
52 builders is a mapping of verbs to tuples of (oai_dc-generating-function,
53 ivo_vor-generating-function, argument-building-function).
54
55 The argument-building function takes the OAI-PMH parameter dictionary
56 (that's already validated for mandatory and optional arguments) and
57 returns a tuple that is then passed on to the generating functions.
58
59 Those must returns stanxml for inclusion in an OAI.PMH element. The
60 response header is generated by this function.
61 """
62 if "verb" not in pars:
63 raise common.BadArgument("verb")
64 verb = pars["verb"]
65
66 if verb not in _ARGUMENTS:
67 raise common.BadVerb("'%s' is an unsupported operation."%verb)
68 requiredArgs, optionalArgs = _ARGUMENTS[verb]
69 checkPars(pars, requiredArgs, optionalArgs)
70
71 contentMaker, getArgs = builders[verb]
72
73 # dispatch on prefix if necessary (contentMaker is a dict)
74 if isinstance(contentMaker, dict):
75 contentMaker = dispatchOnPrefix(pars, contentMaker)
76
77 return OAI.PMH[
78 getResponseHeaders(pars),
79 contentMaker(*getArgs(pars)),]
80
81
82 ########################### parsing and generating resumption tokens
83 # In our implementation, the resumptionToken is a hex-encoded
84 # zlibbed query string made from the parameters, plus information
85 # on the offset and the time the resumption token was issued.
86
87 def makeResumptionToken(pars, nextOffset):
88 """return a resumptionToken element for resuming the query in
89 pars at nextOffset.
90 """
91 toEncode = pars.copy()
92 toEncode["nextOffset"] = str(nextOffset)
93 toEncode["queryDate"] = time.time()
94 return utils.getCleanBytes(
95 urlparse.urlencode(toEncode)).decode("ascii")
96
97
98 def parseResumptionToken(pars):
99 """returns a a dict realPars for an OAI-PMH parameter
100 dictionary pars.
101
102 If we believe that the registry has changed since rawToken's
103 timestamp, we raise a BadResumptionToken exception. This is
104 based on gavo pub reloading the //services RD after publication.
105 Not perfect, but probably adequate.
106
107 Note that newPars will contain resumptionToken again, but as an
108 offset to the query executed.
109 """
110 try:
111 newPars = dict(urlparse.parse_qsl(
112 utils.getDirtyBytes(pars["resumptionToken"]).decode("ascii")))
113 queryDate = float(newPars.pop("queryDate"))
114 offset = int(newPars.pop("nextOffset"))
115 except KeyError:
116 raise base.ui.logOldExc(
117 common.BadResumptionToken("Incomplete resumption token"))
118 except Exception as msg:
119 raise base.ui.logOldExc(common.BadResumptionToken(str(msg)))
120
121 if newPars.get("verb", 1)!=pars.get("verb", 2):
122 raise common.BadResumptionToken(
123 "Trying to resume with a different verb")
124
125 if pars.get("metadataPrefix"):
126 raise common.BadResumptionToken("Trying to resume with a"
127 " different metadata prefix")
128
129 if int(queryDate)<int(base.caches.getRD("//services").loadedAt):
130 raise common.BadResumptionToken("Service table has changed")
131
132 newPars["resumptionToken"] = offset
133 return newPars
134
135 ########################### Helpers for OAI handlers
136
137 def checkPars(pars, required, optional=[],
138 ignored=set(["verb", "maxRecords"])):
139 """raises exceptions for missing or illegal parameters.
140 """
141 required, optional = set(required), set(optional)
142 for name in pars:
143 if name not in ignored and name not in required and name not in optional:
144 raise common.BadArgument(name)
145 for name in required:
146 if name not in pars:
147 raise common.BadArgument(name)
148
149
150 def getResponseHeaders(pars):
151 """returns the OAI response header for a query with pars.
152 """
153 return [
154 OAI.responseDate[datetime.datetime.utcnow().strftime(
155 utils.isoTimestampFmt)],
156 OAI.request(verb=pars["verb"],
157 metadataPrefix=pars.get("metadataPrefix"))]
158
159
160 def dispatchOnPrefix(pars, contentMakers):
161 """returns a resource factory depending on the metadataPrefix in pars.
162
163 contentMakers is one of the dictionaries called "verb" in builders
164 below.
165
166 Invalid metadataPrefixes are detected here and lead to exceptions.
167 """
168 try:
169 return contentMakers[pars["metadataPrefix"]]
170 except KeyError:
171 if "metadataPrefix" in pars:
172 raise common.CannotDisseminateFormat(
173 "%s metadata are not supported"%pars["metadataPrefix"])
174 else:
175 raise common.BadArgument("metadataPrefix missing")
176
177
178 def _getSetNames(pars):
179 """returns a set of requested set names from pars.
180
181 This is ivo_managed if no set is specified in pars.
182 """
183 return set([pars.get("set", "ivo_managed")])
184
185
186 def _makeArgsForListMetadataFormats(pars):
187 # returns arguments for builders.getListMetadataElements.
188 # identifier is not ignored since crooks may be trying to verify the
189 # existence of resource in this way and we want to let them do this.
190 # Of course, we support both kinds of metadata on all records.
191 if "identifier" in pars:
192 identifiers.getResobFromIdentifier(pars["identifier"])
193 return ()
194
195
196 def _addTemporalCondition(parVal, operator, sqlFrags, sqlPars, parName):
197 """generates a temporal condition for recTimestamp and operator out of
198 parVal.
199
200 This is a helper to handle both from and to parameters.
201
202 Nothing is generated if parVal is None.
203
204 Since the Validator insists that servers enforce identical granularity
205 on both arguments, this is more involved; it returns None, "time",
206 or "datetime" depending on what the argument was.
207 """
208 if parVal is None:
209 return None
210
211 parsed, argtype = None, None
212 mat = utils.datetimeRE.match(parVal)
213 if mat:
214 parsed = base.parseDefaultDatetime(parVal)
215 argtype = "datetime"
216
217 mat = utils.dateRE.match(parVal)
218 if not parsed and mat:
219 parsed = base.parseDefaultDate(parVal)
220 # postgres compares dates against timestamps as if the dates were for
221 # midnight. Therefore, on the upper limit, we need to fix things:
222 if operator=='<=':
223 parsed = parsed+datetime.timedelta(1)
224 operator = '<'
225 argtype = "date"
226
227 if parsed:
228 sqlFrags.append("recTimestamp %s %%(%s)s"%(
229 operator,
230 base.getSQLKey("temporal", parsed, sqlPars)))
231 return argtype
232
233 raise common.BadArgument(parName)
234
235
236 def _parseOAIPars(pars):
237 """returns a pair of queryFragment, parameters for a query of
238 services#services according to OAI.
239 """
240 sqlPars, sqlFrags = {}, []
241 argTypes = set(argType for argType in [
242 _addTemporalCondition(
243 pars.get("from"), ">=", sqlFrags, sqlPars, "from"),
244 _addTemporalCondition(
245 pars.get("until"), "<=", sqlFrags, sqlPars, "until")]
246 if argType)
247 if len(argTypes)==2:
248 raise common.BadArgument("from")
249
250 return " AND ".join(sqlFrags), sqlPars
251
252
253 def _getSetCondition(pars, sqlPars):
254 """helps getMatchingRestups.
255 """
256 if "set" in pars:
257 setName = pars["set"]
258 else:
259 setName = "ivo_managed"
260 # we should join for this, but we'd need more careful query
261 # construction then...
262 return ("EXISTS (SELECT setName from dc.sets WHERE"
263 " sets.resId=resources.resId"
264 " AND sets.sourceRD=resources.sourceRD"
265 " AND setname=%%(%s)s)"%(base.getSQLKey("set", setName, sqlPars)))
266
267
268 def getMatchingRows(pars, rscTableDef, getSetFilter):
269 """returns rows in rscTableDef matching the OAI parameters pars.
270
271 The last element of the list could be an OAI.resumptionToken element.
272 pars is a dictionary mapping any of the following keys to values:
273
274 - from
275 - until -- these give a range for which changed records are being returned
276 - set -- maps to a sequence of set names to be matched.
277 - resumptionToken -- some magic value (see OAI.resumptionToken)
278 - maxRecords -- an integer literal that specifies the maximum number
279 of records returned, defaulting to [ivoa]oaipmhPageSize
280
281 maxRecords is not part of OAI-PMH; it is used internally to
282 turn paging on when we think it's a good idea, and for testing.
283
284 rscTableDef has to be a table with a column recTimestamp giving the
285 resource record's updated time.
286
287 getSetFilter(pars, fillers) is a function receiving the PMH parameters
288 dictionary and a dictionary of query fillers and returning, as appropriate,
289 a condition that implements any conditions on sets within pars
290 """
291 frag, fillers = _parseOAIPars(pars)
292 frag = " AND ".join(
293 f for f in [getSetFilter(pars, fillers), frag] if f)
294
295 maxRecords = int(pars.get("maxRecords",
296 base.getConfig("ivoa", "oaipmhPagesize")))
297 offset = pars.get("resumptionToken", 0)
298 fillers.update({"maxRecords": maxRecords, "offset": offset})
299
300 try:
301 res = rscTableDef.doSimpleQuery(
302 fragments=frag,
303 postfix="LIMIT %(maxRecords)s OFFSET %(offset)s",
304 params=fillers)
305
306 if len(res)==maxRecords:
307 # there's probably more data, add a resumption token
308 res.append(OAI.resumptionToken[
309 makeResumptionToken(pars, offset+len(res))])
310 res[-1].addChild = lambda: 0
311
312 except base.DBError:
313 raise base.ui.logOldExc(
314 common.BadArgument("Bad syntax in some parameter value"))
315 except KeyError as msg:
316 raise base.ui.logOldExc(base.Error("Internal error, missing key: %s"%msg))
317 if not res:
318 raise common.NoRecordsMatch(
319 "No resource records match your criteria.")
320 return res
321
322
323 def getMatchingRestups(pars):
324 """returns a list of res tuples matching the OAI query arguments pars.
325
326 See getMatchingRows for details on pars.
327 """
328 td = common.getServicesRD().getById("resources")
329 return getMatchingRows(pars, td, _getSetCondition)
330
331
332 def getMatchingResobs(pars):
333 """returns a list of res objects matching the OAI-PMH pars.
334
335 See getMatchingRestups for details.
336 """
337 res = []
338 for restup in getMatchingRestups(pars):
339 if isinstance(restup, OAI.OAIElement):
340 res.append(restup)
341 else:
342 try:
343 res.append(identifiers.getResobFromRestup(restup))
344 except Exception as exc:
345 base.ui.notifyError("Could not create resource for %s: %s"%(
346 repr(restup),
347 exc))
348 return res
349
350
351 ########################### The registry core
352
353 class RegistryCore(svcs.Core, base.RestrictionMixin):
354 """is a core processing OAI requests.
355
356 Its signature requires a single input key containing the complete
357 args from the incoming request. This is necessary to satisfy the
358 requirement of raising errors on duplicate arguments.
359
360 It returns an ElementTree.
361
362 This core is intended to work the the RegistryRenderer.
363 """
364 name_ = "registryCore"
365
366 inputTableXML = """
367 <inputTable id="_pubregInput">
368 <inputKey name="args" type="raw"
369 multiplicity="single"
370 description="The raw dictionary of input parameters"/>
371 </inputTable>
372 """
373
374 outputTableXML = """<outputTable/>"""
375
376 # builders maps actions to a pair of (thing, function(pars) -> whatever),
377 # where function accepts the oai-pmh parameters and returns the an internal
378 # representation of the response. thing is either a function accepting
379 # this internal representation for verbs not requiring a metadata
380 # prefix, or it is a mapping of metadata prefixes to such functions
381 # otherwise.
382 builders = {
383 "GetRecord": ({
384 "ivo_vor": builders.getVOGetRecordElement,
385 "oai_dc": builders.getDCGetRecordElement},
386 lambda pars: (identifiers.getResobFromIdentifier(pars["identifier"]),)),
387 "ListRecords": ({
388 "ivo_vor": builders.getVOListRecordsElement,
389 "oai_dc": builders.getDCListRecordsElement},
390 lambda pars: (getMatchingResobs(pars), _getSetNames(pars))),
391 "ListIdentifiers": ({
392 "ivo_vor": builders.getListIdentifiersElement,
393 "oai_dc": builders.getListIdentifiersElement},
394 lambda pars: (getMatchingRestups(pars),)),
395 "ListSets": (builders.getListSetsElement,
396 lambda pars: ()),
397 "Identify": (builders.getIdentifyElement,
398 lambda pars: (base.caches.getRD("//services").getById("registry"),)),
399 "ListMetadataFormats": (builders.getListMetadataFormatsElement,
400 _makeArgsForListMetadataFormats),
401 }
402
403 def runWithPMHDict(self, args):
404 pars = {}
405 for argName, argVal in args.items():
406 if len(argVal)!=1:
407 raise common.BadArgument(argName)
408 else:
409 pars[argName] = argVal[0]
410
411 if "resumptionToken" in pars:
412 pars = parseResumptionToken(pars)
413
414 return runPMH(pars, self.builders)
415
416 def run(self, service, inputTable, queryMeta):
417 """returns an ElementTree containing a OAI-PMH response for the query
418 described by pars.
419 """
420 args = inputTable.getParam("args") or {}
421 return self.runWithPMHDict(args)