Debian Codegraph @

gavo/registry/oaiinter.py

raw symbols SCIP
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 datetimescip-python python python-stdlib 3.11 datetime/__init__:
18 import timescip-python python python-stdlib 3.11 time/__init__:
19 import urllib.parsescip-python python python-stdlib 3.11 `urllib.parse`/__init__: as urlparse
20
21 from gavoscip-python python gavodachs 2.13 gavo/__init__: import basescip-python python gavodachs 2.13 `gavo.base`/__init__:
22 from gavoscip-python python gavodachs 2.13 gavo/__init__: import svcsscip-python python gavodachs 2.13 `gavo.svcs`/__init__:
23 from gavoscip-python python gavodachs 2.13 gavo/__init__: import utilsscip-python python gavodachs 2.13 `gavo.utils`/__init__:
24 from gavo.registryscip-python python gavodachs 2.13 `gavo.registry`/__init__: import buildersscip-python python gavodachs 2.13 `gavo.registry.builders`/__init__:
25 from gavo.registryscip-python python gavodachs 2.13 `gavo.registry`/__init__: import commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:
26 from gavo.registryscip-python python gavodachs 2.13 `gavo.registry`/__init__: import identifiersscip-python python gavodachs 2.13 `gavo.registry.identifiers`/__init__:
27 from gavo.registry.modelscip-python python gavodachs 2.13 `gavo.registry.model`/__init__: import OAIscip-python python gavodachs 2.13 `gavo.registry.model`/OAI#
28
29 from gavo.registry.commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__: import ( #noflake: exported names
30 OAIErrorscip-python python gavodachs 2.13 `gavo.registry.common`/OAIError#, BadArgumentscip-python python gavodachs 2.13 `gavo.registry.common`/BadArgument#, BadResumptionTokenscip-python python gavodachs 2.13 `gavo.registry.common`/BadResumptionToken#, BadVerbscip-python python gavodachs 2.13 `gavo.registry.common`/BadVerb#,
31 CannotDisseminateFormatscip-python python gavodachs 2.13 `gavo.registry.common`/CannotDisseminateFormat#, IdDoesNotExistscip-python python gavodachs 2.13 `gavo.registry.common`/IdDoesNotExist#, NoMetadataFormatsscip-python python gavodachs 2.13 `gavo.registry.common`/NoMetadataFormats#,
32 NoSetHierarchyscip-python python gavodachs 2.13 `gavo.registry.common`/NoSetHierarchy#, NoRecordsMatchscip-python python gavodachs 2.13 `gavo.registry.common`/NoRecordsMatch#)
33
34
35 ########################### Generic Processing of PMH requests
36
37 # a mapping of OAI verbs to optional and required argument names
38 _ARGUMENTSscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_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 runPMHscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/runPMH().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/runPMH().(pars), buildersscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/runPMH().(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 parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/runPMH().(pars):
63 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadArgumentscip-python python gavodachs 2.13 `gavo.registry.common`/BadArgument#("verb")
64 verb = parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/runPMH().(pars)["verb"]
65
66 if verb not in _ARGUMENTSscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_ARGUMENTS.:
67 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadVerbscip-python python gavodachs 2.13 `gavo.registry.common`/BadVerb#("'%s' is an unsupported operation."%verb)
68 requiredArgs, optionalArgs = _ARGUMENTSscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_ARGUMENTS.[verb]
69 checkParsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/runPMH().(pars), requiredArgs, optionalArgs)
70
71 contentMaker, getArgs = buildersscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/runPMH().(builders)[verb]
72
73 # dispatch on prefix if necessary (contentMaker is a dict)
74 if isinstance(contentMaker, dictscip-python python python-stdlib 3.11 builtins/dict#):
75 contentMaker = dispatchOnPrefixscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/dispatchOnPrefix().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/runPMH().(pars), contentMaker)
76
77 return OAIscip-python python gavodachs 2.13 `gavo.registry.model`/OAI#.PMHscip-python python gavodachs 2.13 `gavo.registry.model`/OAI#PMH#[
78 getResponseHeadersscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getResponseHeaders().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/runPMH().(pars)),
79 contentMaker(*getArgs(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/runPMH().(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 makeResumptionTokenscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/makeResumptionToken().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/makeResumptionToken().(pars), nextOffsetscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/makeResumptionToken().(nextOffset)):
88 """return a resumptionToken element for resuming the query in
89 pars at nextOffset.
90 """
91 toEncode = parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/makeResumptionToken().(pars).copy()
92 toEncode["nextOffset"] = strscip-python python python-stdlib 3.11 builtins/str#(nextOffsetscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/makeResumptionToken().(nextOffset))
93 toEncode["queryDate"] = timescip-python python python-stdlib 3.11 time/__init__:.timescip-python python python-stdlib 3.11 time/time().()
94 return utilsscip-python python gavodachs 2.13 `gavo.utils`/__init__:.getCleanBytesscip-python python gavodachs 2.13 `gavo.utils.misctricks`/getCleanBytes().(
95 urlparse.urlencode(toEncode)).decodescip-python python python-stdlib 3.11 builtins/bytes#decode().("ascii")
96
97
98 def parseResumptionTokenscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/parseResumptionToken().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/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 = dictscip-python python python-stdlib 3.11 builtins/dict#(urlparse.parse_qsl(
112 utilsscip-python python gavodachs 2.13 `gavo.utils`/__init__:.getDirtyBytesscip-python python gavodachs 2.13 `gavo.utils.misctricks`/getDirtyBytes().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/parseResumptionToken().(pars)["resumptionToken"]).decodescip-python python python-stdlib 3.11 builtins/bytes#decode().("ascii")))
113 queryDate = floatscip-python python python-stdlib 3.11 builtins/float#(newPars.popscip-python python python-stdlib 3.11 builtins/dict#pop().("queryDate"))
114 offset = intscip-python python python-stdlib 3.11 builtins/int#(newPars.popscip-python python python-stdlib 3.11 builtins/dict#pop().("nextOffset"))
115 except KeyErrorscip-python python python-stdlib 3.11 builtins/KeyError#:
116 raise basescip-python python gavodachs 2.13 `gavo.base`/__init__:.uiscip-python python gavodachs 2.13 `gavo.base`/ui..logOldExcscip-python python gavodachs 2.13 `gavo.base.events`/EventDispatcher#logOldExc().(
117 commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadResumptionTokenscip-python python gavodachs 2.13 `gavo.registry.common`/BadResumptionToken#("Incomplete resumption token"))
118 except Exceptionscip-python python python-stdlib 3.11 builtins/Exception# as msg:
119 raise basescip-python python gavodachs 2.13 `gavo.base`/__init__:.uiscip-python python gavodachs 2.13 `gavo.base`/ui..logOldExcscip-python python gavodachs 2.13 `gavo.base.events`/EventDispatcher#logOldExc().(commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadResumptionTokenscip-python python gavodachs 2.13 `gavo.registry.common`/BadResumptionToken#(strscip-python python python-stdlib 3.11 builtins/str#(msg)))
120
121 if newPars.getscip-python python python-stdlib 3.11 builtins/dict#get().("verb", 1)!=parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/parseResumptionToken().(pars).get("verb", 2):
122 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadResumptionTokenscip-python python gavodachs 2.13 `gavo.registry.common`/BadResumptionToken#(
123 "Trying to resume with a different verb")
124
125 if parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/parseResumptionToken().(pars).get("metadataPrefix"):
126 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadResumptionTokenscip-python python gavodachs 2.13 `gavo.registry.common`/BadResumptionToken#("Trying to resume with a"
127 " different metadata prefix")
128
129 if intscip-python python python-stdlib 3.11 builtins/int#(queryDate)<intscip-python python python-stdlib 3.11 builtins/int#(basescip-python python gavodachs 2.13 `gavo.base`/__init__:.cachesscip-python python gavodachs 2.13 `gavo.base.caches`/__init__:.getRD("//services").loadedAt):
130 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadResumptionTokenscip-python python gavodachs 2.13 `gavo.registry.common`/BadResumptionToken#("Service table has changed")
131
132 newPars["resumptionToken"] = offset
133 return newPars
134
135 ########################### Helpers for OAI handlers
136
137 def checkParsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(pars), requiredscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(required), optionalscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(optional)=[],
138 ignoredscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(ignored)=setscip-python python python-stdlib 3.11 builtins/set#(["verb", "maxRecords"])):
139 """raises exceptions for missing or illegal parameters.
140 """
141 requiredscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(required), optionalscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(optional) = setscip-python python python-stdlib 3.11 builtins/set#(requiredscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(required)), setscip-python python python-stdlib 3.11 builtins/set#(optionalscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(optional))
142 for name in parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(pars):
143 if name not in ignoredscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(ignored) and name not in requiredscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(required) and name not in optionalscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(optional):
144 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadArgumentscip-python python gavodachs 2.13 `gavo.registry.common`/BadArgument#(name)
145 for name in requiredscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(required):
146 if name not in parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/checkPars().(pars):
147 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadArgumentscip-python python gavodachs 2.13 `gavo.registry.common`/BadArgument#(name)
148
149
150 def getResponseHeadersscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getResponseHeaders().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getResponseHeaders().(pars)):
151 """returns the OAI response header for a query with pars.
152 """
153 return [
154 OAIscip-python python gavodachs 2.13 `gavo.registry.model`/OAI#.responseDatescip-python python gavodachs 2.13 `gavo.registry.model`/OAI#responseDate#[datetimescip-python python python-stdlib 3.11 datetime/__init__:.datetimescip-python python python-stdlib 3.11 datetime/datetime#.utcnowscip-python python python-stdlib 3.11 datetime/datetime#utcnow().().strftimescip-python python python-stdlib 3.11 datetime/date#strftime().(
155 utilsscip-python python gavodachs 2.13 `gavo.utils`/__init__:.isoTimestampFmtscip-python python gavodachs 2.13 `gavo.utils.texttricks`/isoTimestampFmt.)],
156 OAIscip-python python gavodachs 2.13 `gavo.registry.model`/OAI#.requestscip-python python gavodachs 2.13 `gavo.registry.model`/OAI#request#(verb=parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getResponseHeaders().(pars)["verb"],
157 metadataPrefix=parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getResponseHeaders().(pars).get("metadataPrefix"))]
158
159
160 def dispatchOnPrefixscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/dispatchOnPrefix().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/dispatchOnPrefix().(pars), contentMakersscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/dispatchOnPrefix().(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 contentMakersscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/dispatchOnPrefix().(contentMakers)[parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/dispatchOnPrefix().(pars)["metadataPrefix"]]
170 except KeyErrorscip-python python python-stdlib 3.11 builtins/KeyError#:
171 if "metadataPrefix" in parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/dispatchOnPrefix().(pars):
172 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.CannotDisseminateFormatscip-python python gavodachs 2.13 `gavo.registry.common`/CannotDisseminateFormat#(
173 "%s metadata are not supported"%parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/dispatchOnPrefix().(pars)["metadataPrefix"])
174 else:
175 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadArgumentscip-python python gavodachs 2.13 `gavo.registry.common`/BadArgument#("metadataPrefix missing")
176
177
178 def _getSetNamesscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_getSetNames().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_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 setscip-python python python-stdlib 3.11 builtins/set#([parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_getSetNames().(pars).get("set", "ivo_managed")])
184
185
186 def _makeArgsForListMetadataFormatsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_makeArgsForListMetadataFormats().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_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 parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_makeArgsForListMetadataFormats().(pars):
192 identifiersscip-python python gavodachs 2.13 `gavo.registry.identifiers`/__init__:.getResobFromIdentifierscip-python python gavodachs 2.13 `gavo.registry.identifiers`/getResobFromIdentifier().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_makeArgsForListMetadataFormats().(pars)["identifier"])
193 return ()
194
195
196 def _addTemporalConditionscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(parValscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(parVal), operatorscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(operator), sqlFragsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(sqlFrags), sqlParsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(sqlPars), parNamescip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(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 parValscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(parVal) is None:
209 return None
210
211 parsed, argtype = None, None
212 mat = utilsscip-python python gavodachs 2.13 `gavo.utils`/__init__:.datetimeREscip-python python gavodachs 2.13 `gavo.utils.texttricks`/datetimeRE..matchscip-python python python-stdlib 3.11 re/Pattern#match().(parValscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(parVal))
213 if mat:
214 parsed = basescip-python python gavodachs 2.13 `gavo.base`/__init__:.parseDefaultDatetimescip-python python gavodachs 2.13 `gavo.base.literals`/parseCooPair().(parValscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(parVal))
215 argtype = "datetime"
216
217 mat = utilsscip-python python gavodachs 2.13 `gavo.utils`/__init__:.dateREscip-python python gavodachs 2.13 `gavo.utils.texttricks`/dateRE..matchscip-python python python-stdlib 3.11 re/Pattern#match().(parValscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(parVal))
218 if not parsed and mat:
219 parsed = basescip-python python gavodachs 2.13 `gavo.base`/__init__:.parseDefaultDatescip-python python gavodachs 2.13 `gavo.base.literals`/parseCooPair().(parValscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(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 operatorscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(operator)=='<=':
223 parsed = parsed+datetimescip-python python python-stdlib 3.11 datetime/__init__:.timedeltascip-python python python-stdlib 3.11 datetime/timedelta#(1)
224 operatorscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(operator) = '<'
225 argtype = "date"
226
227 if parsed:
228 sqlFragsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(sqlFrags).append("recTimestamp %s %%(%s)s"%(
229 operatorscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(operator),
230 basescip-python python gavodachs 2.13 `gavo.base`/__init__:.getSQLKeyscip-python python gavodachs 2.13 `gavo.base.sqlmunge`/getSQLKey().("temporal", parsed, sqlParsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(sqlPars))))
231 return argtype
232
233 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadArgumentscip-python python gavodachs 2.13 `gavo.registry.common`/BadArgument#(parNamescip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(parName))
234
235
236 def _parseOAIParsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_parseOAIPars().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_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 = setscip-python python python-stdlib 3.11 builtins/set#(argType for argType in [
242 _addTemporalConditionscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(
243 parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_parseOAIPars().(pars).get("from"), ">=", sqlFrags, sqlPars, "from"),
244 _addTemporalConditionscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_addTemporalCondition().(
245 parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_parseOAIPars().(pars).get("until"), "<=", sqlFrags, sqlPars, "until")]
246 if argType)
247 if len(argTypes)==2:
248 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadArgumentscip-python python gavodachs 2.13 `gavo.registry.common`/BadArgument#("from")
249
250 return " AND ".joinscip-python python python-stdlib 3.11 builtins/str#join().(sqlFrags), sqlPars
251
252
253 def _getSetConditionscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_getSetCondition().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_getSetCondition().(pars), sqlParsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_getSetCondition().(sqlPars)):
254 """helps getMatchingRestups.
255 """
256 if "set" in parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_getSetCondition().(pars):
257 setName = parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_getSetCondition().(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)"%(basescip-python python gavodachs 2.13 `gavo.base`/__init__:.getSQLKeyscip-python python gavodachs 2.13 `gavo.base.sqlmunge`/getSQLKey().("set", setName, sqlParsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_getSetCondition().(sqlPars))))
266
267
268 def getMatchingRowsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(pars), rscTableDefscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(rscTableDef), getSetFilterscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(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 = _parseOAIParsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_parseOAIPars().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(pars))
292 frag = " AND ".joinscip-python python python-stdlib 3.11 builtins/str#join().(
293 f for f in [getSetFilterscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(getSetFilter)(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(pars), fillers), frag] if f)
294
295 maxRecords = intscip-python python python-stdlib 3.11 builtins/int#(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(pars).get("maxRecords",
296 basescip-python python gavodachs 2.13 `gavo.base`/__init__:.getConfigscip-python python gavodachs 2.13 `gavo.base.config`/get.("ivoa", "oaipmhPagesize")))
297 offset = parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(pars).get("resumptionToken", 0)
298 fillers.updatescip-python python python-stdlib 3.11 typing/MutableMapping#update().({"maxRecords": maxRecords, "offset": offset})
299
300 try:
301 res = rscTableDefscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(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(OAIscip-python python gavodachs 2.13 `gavo.registry.model`/OAI#.resumptionTokenscip-python python gavodachs 2.13 `gavo.registry.model`/OAI#resumptionToken#[
309 makeResumptionTokenscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/makeResumptionToken().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(pars), offset+len(res))])
310 res[-1].addChild = lambda: 0
311
312 except basescip-python python gavodachs 2.13 `gavo.base`/__init__:.DBErrorscip-python python gavodachs 2.13 `psycopg2._psycopg`/DBError#:
313 raise basescip-python python gavodachs 2.13 `gavo.base`/__init__:.uiscip-python python gavodachs 2.13 `gavo.base`/ui..logOldExcscip-python python gavodachs 2.13 `gavo.base.events`/EventDispatcher#logOldExc().(
314 commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadArgumentscip-python python gavodachs 2.13 `gavo.registry.common`/BadArgument#("Bad syntax in some parameter value"))
315 except KeyErrorscip-python python python-stdlib 3.11 builtins/KeyError# as msg:
316 raise basescip-python python gavodachs 2.13 `gavo.base`/__init__:.uiscip-python python gavodachs 2.13 `gavo.base`/ui..logOldExcscip-python python gavodachs 2.13 `gavo.base.events`/EventDispatcher#logOldExc().(basescip-python python gavodachs 2.13 `gavo.base`/__init__:.Errorscip-python python gavodachs 2.13 `gavo.base.structure`/Structure#("Internal error, missing key: %s"%msg))
317 if not res:
318 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.NoRecordsMatchscip-python python gavodachs 2.13 `gavo.registry.common`/NoRecordsMatch#(
319 "No resource records match your criteria.")
320 return res
321
322
323 def getMatchingRestupsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRestups().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/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 = commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.getServicesRDscip-python python gavodachs 2.13 `gavo.registry.common`/getServicesRD().().getById("resources")
329 return getMatchingRowsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRows().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRestups().(pars), td, _getSetConditionscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_getSetCondition().)
330
331
332 def getMatchingResobsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingResobs().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/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 getMatchingRestupsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRestups().(parsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingResobs().(pars)):
339 if isinstance(restup, OAIscip-python python gavodachs 2.13 `gavo.registry.model`/OAI#.OAIElementscip-python python gavodachs 2.13 `gavo.registry.model`/OAI#OAIElement#):
340 res.appendscip-python python python-stdlib 3.11 builtins/list#append().(restup)
341 else:
342 try:
343 res.appendscip-python python python-stdlib 3.11 builtins/list#append().(identifiersscip-python python gavodachs 2.13 `gavo.registry.identifiers`/__init__:.getResobFromRestupscip-python python gavodachs 2.13 `gavo.registry.identifiers`/getResobFromRestup().(restup))
344 except Exceptionscip-python python python-stdlib 3.11 builtins/Exception# as exc:
345 basescip-python python gavodachs 2.13 `gavo.base`/__init__:.uiscip-python python gavodachs 2.13 `gavo.base`/ui..notifyErrorscip-python python gavodachs 2.13 `gavo.base.events`/EventDispatcher#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 RegistryCorescip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#(svcsscip-python python gavodachs 2.13 `gavo.svcs`/__init__:.Corescip-python python gavodachs 2.13 `gavo.svcs.core`/Core#, basescip-python python gavodachs 2.13 `gavo.base`/__init__:.RestrictionMixinscip-python python gavodachs 2.13 `gavo.base.structure`/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_scip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#name_. = "registryCore"
365
366 inputTableXMLscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#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 outputTableXMLscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#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 buildersscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#builders. = {
383 "GetRecord": ({
384 "ivo_vor": buildersscip-python python gavodachs 2.13 `gavo.registry.builders`/__init__:.getVOGetRecordElementscip-python python gavodachs 2.13 `gavo.registry.builders`/getVOGetRecordElement().,
385 "oai_dc": buildersscip-python python gavodachs 2.13 `gavo.registry.builders`/__init__:.getDCGetRecordElementscip-python python gavodachs 2.13 `gavo.registry.builders`/getDCGetRecordElement().},
386 lambda pars: (identifiersscip-python python gavodachs 2.13 `gavo.registry.identifiers`/__init__:.getResobFromIdentifierscip-python python gavodachs 2.13 `gavo.registry.identifiers`/getResobFromIdentifier().(pars["identifier"]),)),
387 "ListRecords": ({
388 "ivo_vor": buildersscip-python python gavodachs 2.13 `gavo.registry.builders`/__init__:.getVOListRecordsElementscip-python python gavodachs 2.13 `gavo.registry.builders`/getVOListRecordsElement().,
389 "oai_dc": buildersscip-python python gavodachs 2.13 `gavo.registry.builders`/__init__:.getDCListRecordsElementscip-python python gavodachs 2.13 `gavo.registry.builders`/getDCListRecordsElement().},
390 lambda pars: (getMatchingResobsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingResobs().(pars), _getSetNamesscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_getSetNames().(pars))),
391 "ListIdentifiers": ({
392 "ivo_vor": buildersscip-python python gavodachs 2.13 `gavo.registry.builders`/__init__:.getListIdentifiersElementscip-python python gavodachs 2.13 `gavo.registry.builders`/getListIdentifiersElement().,
393 "oai_dc": buildersscip-python python gavodachs 2.13 `gavo.registry.builders`/__init__:.getListIdentifiersElementscip-python python gavodachs 2.13 `gavo.registry.builders`/getListIdentifiersElement().},
394 lambda pars: (getMatchingRestupsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/getMatchingRestups().(pars),)),
395 "ListSets": (buildersscip-python python gavodachs 2.13 `gavo.registry.builders`/__init__:.getListSetsElementscip-python python gavodachs 2.13 `gavo.registry.builders`/getListSetsElement().,
396 lambda pars: ()),
397 "Identify": (buildersscip-python python gavodachs 2.13 `gavo.registry.builders`/__init__:.getIdentifyElementscip-python python gavodachs 2.13 `gavo.registry.builders`/getIdentifyElement().,
398 lambda pars: (basescip-python python gavodachs 2.13 `gavo.base`/__init__:.cachesscip-python python gavodachs 2.13 `gavo.base.caches`/__init__:.getRD("//services").getById("registry"),)),
399 "ListMetadataFormats": (buildersscip-python python gavodachs 2.13 `gavo.registry.builders`/__init__:.getListMetadataFormatsElementscip-python python gavodachs 2.13 `gavo.registry.builders`/getListMetadataFormatsElement().,
400 _makeArgsForListMetadataFormatsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/_makeArgsForListMetadataFormats().),
401 }
402
403 def runWithPMHDictscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#runWithPMHDict().(selfscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#runWithPMHDict().(self), argsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#runWithPMHDict().(args)):
404 pars = {}
405 for argName, argVal in argsscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#runWithPMHDict().(args).items():
406 if len(argVal)!=1:
407 raise commonscip-python python gavodachs 2.13 `gavo.registry.common`/__init__:.BadArgumentscip-python python gavodachs 2.13 `gavo.registry.common`/BadArgument#(argName)
408 else:
409 pars[argName] = argVal[0]
410
411 if "resumptionToken" in pars:
412 pars = parseResumptionTokenscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/parseResumptionToken().(pars)
413
414 return runPMHscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/runPMH().(pars, selfscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#runWithPMHDict().(self).buildersscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#builders.)
415
416 def runscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#run().(selfscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#run().(self), servicescip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#run().(service), inputTablescip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#run().(inputTable), queryMetascip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#run().(queryMeta)):
417 """returns an ElementTree containing a OAI-PMH response for the query
418 described by pars.
419 """
420 args = inputTablescip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#run().(inputTable).getParam("args") or {}
421 return selfscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#run().(self).runWithPMHDictscip-python python gavodachs 2.13 `gavo.registry.oaiinter`/RegistryCore#runWithPMHDict().(args)