Debian Codegraph @

gavo/registry/builders.py

raw
1 """
2 Functions returning xmlstan for various OAI/VOR documents.
3
4 This comprises basic VOResource elements; capabilities and interfaces
5 (i.e. everything to do with renderers) are in registry.capabilities.
6
7 All this only becomes difficult when actually generating VOResource
8 metadata (OAI is plain). For every type of VO resource (CatalogService,
9 Registry, etc), there's a XYResourceMaker, all inheriting ResourceMaker.
10
11 The decision what VOResource type a given service has is passed
12 using common.getResType; this means the resType meta is tried first,
13 using resob.resType as a fallback.
14 """
15
16 #c Copyright 2008-2025, the GAVO project <[email protected]>
17 #c
18 #c This program is free software, covered by the GNU GPL. See the
19 #c COPYING file in the source distribution.
20
21
22 # DataCollection mess: In rev 3769, we experimentally pushed out
23 # CatalogService records instead of DataCollections, trying to have
24 # capabilities for them. That didn't turn out well even though
25 # we didn't do that for SIA and frieds: All-VO discovery of a
26 # given service type is a very typical use case. So, we backed
27 # that out again in rev. 3883, though the support code remains.
28 #
29 # Then, in rev. 3891, we went back to CatalogService records, only
30 # this time we only pushed out capabilities with "auxiliary" standard ids.
31
32
33 from gavo import base
34 from gavo import stc
35 from gavo import svcs
36 from gavo import utils
37 from gavo.base import meta
38 from gavo.registry import common
39 from gavo.registry import capabilities
40 from gavo.registry import identifiers
41 from gavo.registry import tableset
42 from gavo.registry import servicelist
43 from gavo.registry.model import (
44 OAI, VOR, VOG, DC, RI, VS, OAIDC, VSTD, DOC)
45
46 MS = base.makeStruct
47
48 SF = meta.stanFactory
49 _defaultSet = set(["ivo_managed"])
50 # Set this to False to disable some lame "don't fail" error handlings;
51 # this will raise more exceptions and is not recommended in the actual
52 # OAI interface (where *some* info is better than none at all).
53 VALIDATING = False
54
55
56 ################## ModelBasedBuilders for simple metadata handling
57
58 def _build_source(children, localattrs=None):
59 # in source, we try to recognize bibcodes automatically, hence we have
60 # this manual builder.
61 src = str(children[0])
62 attrs = {}
63 if utils.couldBeABibcode(src):
64 attrs["format"] = "bibcode"
65 return VOR.source(**attrs)[src]
66
67
68 def _build_dateFromNews(children, localattrs={}):
69 # _news was designed to be non-VOResource, but it turned out it's
70 # really useful to specify dates. So, contrary to our principle, there's
71 # an underscore-starting meta here, anyway.
72 if utils.dateRE.match(localattrs.get("date", "")):
73 return [VOR.date(role=localattrs.get("role", "Updated"))[
74 localattrs["date"]]]
75
76
77 _vrResourceBuilder = meta.ModelBasedBuilder([
78 ('title', SF(VOR.title)),
79 ('shortName', SF(VOR.shortName)),
80 ('identifier', SF(VOR.identifier)),
81 ('doi', lambda args, localattrs=None: VOR.altIdentifier["doi:"+args[0]]),
82 (None, SF(VOR.curation), [
83 ('publisher', SF(VOR.publisher), (), {
84 "ivoId": "ivoId"}),
85 ('creator', SF(VOR.creator), [
86 ('name', SF(VOR.name), (), {
87 'altIdentifier': "altIdentifier"}),
88 ('logo', SF(VOR.logo)),]),
89 ('contributor', SF(VOR.contributor), (), {
90 "ivoId": "ivoId",
91 'altIdentifier': "altIdentifier"}),
92 ('_dataUpdated', SF(VOR.date, role="Updated")),
93 ('date', SF(VOR.date), (), {
94 "role": "role"}),
95 ('_news', _build_dateFromNews, (), {
96 "role": "role",
97 "date": "date"}),
98 ('version', SF(VOR.version)),
99 ('contact', SF(VOR.contact), [
100 ('name', SF(VOR.name), (), {
101 "ivoId": "ivoId"}),
102 ('address', SF(VOR.address)),
103 ('email', SF(VOR.email)),
104 ('telephone', SF(VOR.telephone)),]),]),
105 (None, SF(VOR.content), [
106 ('subject', SF(VOR.subject)),
107 ('description', SF(VOR.description)),
108 ('source', _build_source),
109 ('referenceURL', SF(VOR.referenceURL)),
110 ('type', SF(VOR.type)),
111 ('contentLevel', SF(VOR.contentLevel)),] + [
112 # old-style relationship terms from VOResource 1.0 f
113 # plan: after a while, make the update mapping in here
114 (None, SF(lambda t=vorTerm:
115 VOR.relationship[VOR.relationshipType[t]]), [
116 (metaName, SF(VOR.relatedResource), (), {
117 "ivoId": "ivoId",
118 "altIdentifier": "altIdentifier"})])
119 for metaName, vorTerm in [
120 ("servedBy", "IsServedBy"),
121 ("serviceFor", "IsServiceFor"),
122 ("derivedFrom", "IsDerivedFrom"),
123 ("relatedTo", "related-to"),
124 ("mirrorOf", "IsIdenticalTo"),
125 ("uses", "Cites")]
126 ] + [
127 # new-style relationship terms from VOResource 1.1
128 (None, SF(lambda term=term:
129 VOR.relationship[VOR.relationshipType[term]]), [
130 (term[0].lower()+term[1:], SF(VOR.relatedResource), (), {
131 "ivoId": "ivoId",
132 "altIdentifier": "altIdentifier"})])
133 for term in [
134 "Cites",
135 "IsSupplementTo",
136 "IsSupplementedBy",
137 "IsContinuedBy",
138 "Continues",
139 "IsNewVersionOf",
140 "IsPreviousVersionOf",
141 "IsPartOf",
142 "HasPart",
143 "IsSourceOf",
144 "IsDerivedFrom",
145 "IsIdenticalTo",
146 "IsServiceFor",
147 "IsServedBy"]])
148 ])
149
150
151 _dcBuilder = meta.ModelBasedBuilder([
152 ('title', SF(DC.title)),
153 ('identifier', SF(DC.identifier)),
154 ('creator', None, [
155 ('name', SF(DC.creator))]),
156 ('contributor', None, [
157 ('name', SF(DC.contributor))]),
158 ('description', SF(DC.description)),
159 ('language', SF(DC.language)),
160 ('rights', SF(DC.rights), ()),
161 ('publisher', SF(DC.publisher)),
162 ])
163
164
165 _oaiHeaderBuilder = meta.ModelBasedBuilder([
166 ('identifier', SF(OAI.identifier)),
167 ('_metadataUpdated', SF(OAI.datestamp)),
168 ('sets', SF(OAI.setSpec))])
169
170
171 _orgMetaBuilder = meta.ModelBasedBuilder([
172 ('facility', SF(VOR.facility), (),
173 {"altIdentifier": "altIdentifier", "ivoId": "ivoId"}),
174 ('instrument', SF(VOR.instrument), (),
175 {"altIdentifier": "altIdentifier", "ivoId": "ivoId"}),
176 ])
177
178
179 _standardsMetaBuilder = meta.ModelBasedBuilder([
180 ('endorsedVersion', SF(VSTD.endorsedVersion), (), {
181 'status': 'status',
182 'use': 'use'}),
183 ('deprecated', SF(VSTD.deprecated), ()),
184 ('key', SF(VSTD.key), [
185 ('name', SF(VSTD.name), []),
186 ('description', SF(VSTD.description), [])])])
187
188
189 def _stcResourceProfile(metaValue, localattrs=None):
190 # This is a helper for the coverageMetaBuilder; it expects
191 # STC-S and will return an STC resource profile for literal
192 # embedding.
193 if not metaValue:
194 return None
195 try:
196 return stc.astToStan(
197 stc.parseSTCS(metaValue[0]),
198 stc.STC.STCResourceProfile)
199 except Exception as exc:
200 if VALIDATING:
201 raise
202 base.ui.notifyError("Coverage profile '%s' bad while generating "
203 " registry (%s). It is left out."%(metaValue, str(exc)))
204
205
206 def _build_footprintURL(children, localattrs):
207 # a service that has a spatial coverage can spit out
208 # MOCs using the coverage renderer.
209 #
210 # Unfortunately, getting a URL from coverage information breaks
211 # our abstractions. I'd like to get rid of footprintURL anyway,
212 # so this is another case for stealing variables from upstack.
213 # It turns out the macroPackage in the enclosing frame actually
214 # is the service or table we're building for. And if that thing
215 # can build URLs, that's what we're looking for. If it can't
216 # it can't produce footprint MOCs in the first place, so we
217 # can return None.
218 carrier = utils.stealVar("macroPackage")
219 if isinstance(carrier, svcs.Service):
220 return VS.footprint(ivoId="ivo://ivoa.net/std/moc")[
221 carrier.getURL("coverage")]
222
223
224 _coverageMetaBuilder = meta.ModelBasedBuilder([
225 ('coverage', SF(VS.coverage), [
226 ('profile', _stcResourceProfile),
227 ('spatial', SF(VS.spatial)),
228 ('temporal', SF(VS.temporal)),
229 ('spectral', SF(VS.spectral)),
230 # resources that have spatial coverage get a footprint url in
231 # addition to the spatial coverage at least for a while.
232 ('spatial', _build_footprintURL),
233 ('waveband', SF(VS.waveband)),
234 ('regionOfRegard', SF(VS.regionOfRegard)),
235 ]),
236 ('productTypeServed', SF(VS.productTypeServed)),
237 ('dataSource', SF(VS.dataSource)),])
238
239
240 def getResourceArgs(resob):
241 """returns the mandatory attributes for constructing a Resource record
242 for service in a dictionary.
243 """
244 return {
245 "created": base.getMetaText(resob, "creationDate", propagate=True),
246 "updated": base.getMetaText(resob, "_metadataUpdated", propagate=True),
247 "status": base.getMetaText(resob, "status", default="active"),
248 }
249
250
251 def getOAIHeaderElementForRestup(restup):
252 if isinstance(restup, OAI.OAIElement):
253 return restup
254 status = None
255 if restup["deleted"]:
256 status = "deleted"
257 return OAI.header(status=status)[
258 OAI.identifier[identifiers.computeIdentifierFromRestup(restup)],
259 OAI.datestamp[restup["recTimestamp"].strftime(utils.isoTimestampFmt)],
260 [
261 OAI.setSpec[setName]
262 for setName in servicelist.getSetsForResource(restup)]]
263
264
265 ###################### Direct children of OAI.PMH
266
267 def _getOAIURL(registryService):
268 """returns the OAI-PHM access URL for a registry service.
269
270 We don't want to just use getURL(pubreg) since the publication
271 may (and for the publishing registry does) have an accessURL meta.
272 """
273 oaiAccessURL = registryService.getURL("pubreg.xml")
274 for pub in registryService.publications:
275 if pub.render=="pubreg.xml":
276 oaiAccessURL = base.getMetaText(
277 pub, "accessURL", macroPackage=pub.parent)
278 break
279 return oaiAccessURL
280
281
282 def getIdentifyElement(registryService):
283 """returns OAI Identify stanxml.
284
285 registryService is the registry we're identifying, i.e. typically
286 __system__/services#registry
287 """
288 return OAI.Identify[
289 OAI.repositoryName[base.getMetaText(registryService, "title")],
290 OAI.baseURL[_getOAIURL(registryService)],
291 OAI.protocolVersion["2.0"],
292 OAI.adminEmail[base.getMetaText(registryService, "contact.email")],
293 OAI.earliestDatestamp["1970-01-01T00:00:00Z"],
294 OAI.deletedRecord["transient"],
295 OAI.granularity["YYYY-MM-DDThh:mm:ssZ"],
296 OAI.description[
297 getVORMetadataElement(registryService),
298 ],
299 ]
300
301
302 def getListIdentifiersElement(restups):
303 """returns an OAI ListIdentifiers element for the rec tuples recs.
304 """
305 return OAI.ListIdentifiers[
306 [getOAIHeaderElementForRestup(restup) for restup in restups],
307 ]
308
309
310 def getListMetadataFormatsElement():
311 return OAI.ListMetadataFormats[[
312 OAI.metadataFormat[
313 OAI.metadataPrefix[prefix],
314 OAI.schema[schema],
315 OAI.metadataNamespace[ns],
316 ] for prefix, schema, ns in common.METADATA_PREFIXES]
317 ]
318
319
320 def getListSetsElement():
321 return OAI.ListSets[[
322 # XXX TODO: Add some kind of description, in particular when we define
323 # real local sets.
324 OAI.set[
325 OAI.setSpec[set["setName"]],
326 OAI.setName[set["setName"]],
327 ]
328 for set in servicelist.getSets()]]
329
330
331 def getResourceElement(resob, setNames, metadataMaker):
332 """helps get[VO|DC]ResourceElement.
333 """
334 if isinstance(resob, OAI.OAIElement):
335 return resob
336 status = None
337 if base.getMetaText(resob, "status")=="deleted":
338 status = "deleted"
339 return OAI.record[
340 OAI.header(status=status)[
341 _oaiHeaderBuilder.build(resob)],
342 OAI.metadata[
343 metadataMaker(resob, setNames)
344 ]
345 ]
346
347
348 def getDCMetadataElement(resob, setNames):
349 return OAIDC.dc[_dcBuilder.build(resob)]
350
351
352 def getDCResourceElement(resob, setNames=_defaultSet):
353 return getResourceElement(resob, setNames, getDCMetadataElement)
354
355
356 def getDCListRecordsElement(resobs, setNames,
357 makeRecord=getDCResourceElement):
358 """returns stanxml for ListRecords in dublin core format.
359
360 resobs is a sequence of res objects.
361 makeRecord(resob, setNames) -> stanxml is a function that returns
362 an OAI.record element. For ivo_vor metadata prefixes, this is overridden.
363 by getVOListRecordsElement.
364 """
365 recs = OAI.ListRecords()
366 for resob in resobs:
367 try:
368 recs[makeRecord(resob, setNames)]
369 except base.NoMetaKey as msg:
370 base.ui.notifyError("Cannot create registry record for %s#%s"
371 " because mandatory meta %s is missing"%(
372 resob.rd.sourceId, resob.id, msg))
373 except Exception as msg:
374 base.ui.notifyError("Cannot create registry record %s. Reason: %s"%(
375 resob, msg))
376 return recs
377
378
379 def getDCGetRecordElement(resob):
380 return OAI.GetRecord[
381 getDCResourceElement(resob)]
382
383
384 ################### VOResource metadata element creation
385
386 class ResourceMaker(object):
387 """A base class for the generation of VOResource elements.
388
389 These have a resType attribute specifying which resource type
390 they work for. These types are computed by the getResourceType
391 helper function.
392
393 The makeResource function below tries the ResourceMakers in turn
394 for the "best" one that matches.
395
396 If you create new ResourceMakers, you will have to enter them
397 *in the correct sequence* in the _resourceMakers list below.
398
399 ResourceMaker instances are called with a resob argument and a set
400 of set names. You will want to override the _makeResource(resob)
401 -> xmlstan method and probably the resourceClass element.
402 """
403 resourceClass = RI.Resource
404 resType = None
405
406 def _loadDependencies(self, resob):
407 """loads all RDs dependent on resob.rd (if present).
408
409 The dependencies are taken from the dc.res_dependencies table. There,
410 they are typically introduced by served-by relationships (see also
411 service.declareServes.
412 """
413 if not hasattr(resob.rd, "cached dependencies"):
414 deps = common.getDependencies(resob.rd.sourceId)
415 setattr(resob.rd, "cached dependencies", deps)
416 else:
417 deps = getattr(resob.rd, "cached dependencies")
418 for dep in deps:
419 base.caches.getRD(dep)
420
421
422 def _makeResource(self, resob, setNames):
423 self._loadDependencies(resob)
424 res = self.resourceClass(**getResourceArgs(resob))[
425 VOR.validationLevel(validatedBy=str(resob.getMeta("validatedBy")))[
426 resob.getMeta("validationLevel")],
427 _vrResourceBuilder.build(resob),]
428 # Hack the ri prefix so vr:Resource actually becomes a global
429 # element (we should probably change the builder to use ri:Resource
430 # from the start).
431 res._prefix = "ri"
432 return res
433
434 def __call__(self, resob, setNames):
435 return self._makeResource(resob, setNames)
436
437
438 _rightsBuilder = meta.ModelBasedBuilder([
439 ('rights', SF(VOR.rights), (), {
440 'rightsURI': 'rightsURI'}),])
441
442
443 class ServiceResourceMaker(ResourceMaker):
444 """A ResourceMaker adding rights and capabilities.
445
446 For DaCHS, this is basically abstract; these are missing organisational
447 and coverage metadata, and this is probably not useful. Still, if
448 you want to select such a resource type, you can say the equivalent of
449 setMeta("resType", "nonTabularService").
450 """
451 resourceClass = VS.DataService
452 resType = "nonTabularService"
453
454 def _makeResource(self, service, setNames):
455 res = ResourceMaker._makeResource(self, service, setNames)[
456 _rightsBuilder.build(service)]
457 return res[[
458 capabilities.getCapabilityElement(pub)
459 for pub in service.getPublicationsForSet(setNames)]]
460
461
462 class DataServiceResourceMaker(ServiceResourceMaker):
463 """A ResourceMaker for DataServices.
464
465 These are services that may have instrument, facility, and coverage
466 metas but have no associated tables. _computeResourceType in service.py
467 will assign this to services that don't declare an output table.
468 """
469 resourceClass = VS.DataService
470 resType = "dataService"
471
472 def _makeResource(self, service, setNames):
473 return ServiceResourceMaker._makeResource(self, service, setNames)[
474 _orgMetaBuilder.build(service),
475 _coverageMetaBuilder.build(service)]
476
477
478 class CatalogServiceResourceMaker(DataServiceResourceMaker):
479 resourceClass = VS.CatalogService
480 resType = "catalogService"
481 def _makeResource(self, service, setNames):
482 return DataServiceResourceMaker._makeResource(self, service, setNames)[
483 tableset.getTablesetForService(service)]
484
485
486 _registryMetaBuilder = meta.ModelBasedBuilder([
487 ('managedAuthority', SF(VOG.managedAuthority)),])
488
489
490 class RegistryResourceMaker(ServiceResourceMaker):
491 resourceClass = VOG.Resource
492 resType = "registry"
493
494 def _makeResource(self, registry, setNames):
495 return ServiceResourceMaker._makeResource(self, registry, setNames) [
496 VOG.full[base.getMetaText(registry, "full", "false")],
497 _registryMetaBuilder.build(registry),
498 tableset.getTablesetForService(registry)]
499
500
501 class OrgResourceMaker(ResourceMaker):
502 resourceClass = VOR.Organisation
503 resType = "organization"
504 def _makeResource(self, registry, setNames):
505 return ResourceMaker._makeResource(self, registry, setNames) [
506 _orgMetaBuilder.build(registry)]
507
508
509 class AuthResourceMaker(ResourceMaker):
510 resourceClass = VOG.Authority
511 resType = "authority"
512 def _makeResource(self, registry, setNames):
513 return ResourceMaker._makeResource(self, registry, setNames) [
514 VOG.managingOrg(
515 ivoId=base.getMetaText(registry, "managingOrg.ivo-id", default=None))[
516 base.getMetaText(registry, "managingOrg")]]
517
518
519 class StandardsResourceMaker(ResourceMaker):
520 resourceClass = VSTD.Standard
521 resType = "standard"
522 def _makeResource(self, registry, setNames):
523 return ResourceMaker._makeResource(self, registry, setNames) [
524 _standardsMetaBuilder.build(registry)]
525
526
527 class DocResourceMaker(CatalogServiceResourceMaker):
528 resourceClass = DOC.Document
529 resType = "document"
530
531
532 class DeletedResourceMaker(ResourceMaker):
533 resType = "deleted"
534 def _makeResource(self, res, setNames):
535 return []
536
537
538 class DataCollectionResourceMaker(ResourceMaker):
539 """A base class for Table- and DataResourceMaker.
540 """
541 resourceClass = VS.CatalogResource
542
543 def _makeTableset(self, schemas):
544 return tableset.getTablesetForSchemaCollection(schemas)
545
546 def _makeResourceForSchemas(self, metaCarrier, schemas, setNames):
547 """returns xmlstan for schemas within metaCarrier.
548
549 metaCarrier has to provide all the VOR metadata. schemas is a
550 sequence of triples of (rd, tables); rd is used to define a
551 VODataService schema, tables is a sequence of TableDefs that
552 define the tables within that schema.
553 """
554 res = ResourceMaker._makeResource(self, metaCarrier, setNames)[[
555 capabilities.getCapabilityElement(pub)
556 for pub in metaCarrier.getPublicationsForSet(setNames)],
557 _orgMetaBuilder.build(metaCarrier),
558 _coverageMetaBuilder.build(metaCarrier),
559 self._makeTableset(schemas)]
560 return res
561
562
563 class TableResourceMaker(DataCollectionResourceMaker):
564 """A ResourceMaker for rscdef.TableDef items (yielding reformed
565 DataCollections)
566 """
567 resType = "table"
568
569 def _makeResource(self, td, setNames):
570 return DataCollectionResourceMaker._makeResourceForSchemas(
571 self, td, [(td.rd, [td])], setNames)
572
573
574 class DataResourceMaker(DataCollectionResourceMaker):
575 """A ResourceMaker for rscdef.DataDescriptor items (yielding reformed
576 DataCollections)
577 """
578 resType = "data"
579
580 def _makeResource(self, dd, setNames):
581 return DataCollectionResourceMaker._makeResourceForSchemas(
582 self, dd, [(dd.rd, set(dd.iterTableDefs()))], setNames)
583
584
585 class RDResourceMaker(DataCollectionResourceMaker):
586 resType = "rd"
587
588 def _iterCapabilities(self, rd, setNames):
589 """returns capabilities elements for all services on this RD.
590
591 To give operators a chance to influence what is being published,
592 this evaluates the publishedRenderers property documented in the
593 Service docstring.
594
595 I'll not create any VOSI caps here. These don't really work in
596 multi-cap situations anyway.
597 """
598 for s in rd.services:
599 renderProp = s.getProperty("publishedRenderers", [])
600 if renderProp:
601 toPublish = [s.strip() for s in renderProp.split(",")]
602 else:
603 toPublish = s.allowed
604
605 for renderer in toPublish:
606 fakePub = base.makeStruct(svcs.Publication,
607 sets=setNames,
608 service=s,
609 render=renderer)
610 for m in s.iterMeta("description"):
611 fakePub.setMeta("description", m)
612 fakePub.parent = rd
613 yield capabilities.getCapabilityElement(fakePub)
614
615 def _makeResource(self, rd, setNames):
616 ts = tableset.getTablesetForRD(rd)
617
618 tapAuxCap = []
619 if ts and "ivo_managed" in setNames:
620 # Add a TAP aux capability if there are queriable tables.
621 # This will become questionable as soon as we include non-
622 # ADQL tables in our tableset.
623 fakePub = base.makeStruct(svcs.Publication,
624 sets={"ivo_managed"},
625 service=base.resolveCrossId("//tap#run"),
626 render="dali",
627 auxiliary=True)
628 tapAuxCap = capabilities.getCapabilityElement(fakePub)
629
630 return DataCollectionResourceMaker._makeResource(self, rd, setNames)[
631 self._iterCapabilities(rd, setNames),
632 tapAuxCap,
633 _orgMetaBuilder.build(rd),
634 _coverageMetaBuilder.build(rd),
635 ts]
636
637
638 _getResourceMaker = utils.buildClassResolver(ResourceMaker,
639 list(globals().values()), instances=True,
640 key=lambda obj: obj.resType)
641
642
643 def getVORMetadataElement(resob, setNames=_defaultSet):
644 return _getResourceMaker(common.getResType(resob))(resob, setNames)
645
646
647 def getVOResourceElement(resob, setNames=_defaultSet):
648 """returns a stanxml for Resource in VOR format.
649
650 There's trouble here in that we have set management on the level of
651 renderers (capabilities). Thus, to come up with capabilities for
652 a given ivorn, we have to know what set is queried. However,
653 OAI GetRecord doesn't specify sets. So, we provide a default
654 set of ivo_managed, assuming that the registry is only interested
655 in records actually VO-registred. This may fly into our face,
656 but I can't see a way around it given the way our services are
657 described.
658 """
659 return getResourceElement(resob, setNames, getVORMetadataElement)
660
661
662 def getVOListRecordsElement(resobs, setNames):
663 return getDCListRecordsElement(resobs, setNames,
664 getVOResourceElement)
665
666
667 def getVOGetRecordElement(resob):
668 return OAI.GetRecord[
669 getVOResourceElement(resob)]