Debian Codegraph @

gavo/protocols/datalink.py

raw
1 """
2 The datalink core and its numerous helper classes.
3
4 More on this in "Datalink Cores" in the reference documentation.
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 contextlib
14 import itertools
15 import inspect
16 import os
17 import urllib.request, urllib.parse, urllib.error
18
19 from gavo import base
20 from gavo import formats
21 from gavo import rsc
22 from gavo import rscdef
23 from gavo import svcs
24 from gavo import utils
25 from gavo.formal import nevowc
26 from gavo.formats import votablewrite
27 from gavo.protocols import dlasync
28 from gavo.protocols import products
29 from gavo.protocols import soda
30 from gavo.protocols.soda import (FormatNow, DeliverNow, DatalinkFault,
31 DEFAULT_SEMANTICS)
32 from gavo.utils import fitstools
33 from gavo.utils import pyfits
34 from gavo.votable import V, modelgroups
35
36 from twisted.web import static
37
38 LINKS_STANDARD_ID = "ivo://ivoa.net/std/datalink#links-1.1"
39 SYNC_STANDARD_ID = "ivo://ivoa.net/std/soda#sync-1.0"
40 ASYNC_STANDARD_ID = "ivo://ivoa.net/std/soda#async-1.0"
41
42 MS = base.makeStruct
43
44
45 class DatalinkDescriptorMixin:
46 """some generally useful attributes that various code expects datalink
47 descriptors to have.
48
49 These are the makeLink/makeLinkFromFile methods, but also data (where
50 SODA processors accumulate the data they will serve), forSemantics
51 (the semantics we are trying to produce) and contentQualifier
52 (the sort of data at the other end; only touch this if you expect
53 your link to be sent through SAMP).
54 """
55 data = None
56 forSemantics = DEFAULT_SEMANTICS
57 contentQualifier = None
58
59 def makeLink(self, url, **kwargs):
60 """returns a LinkDef for this descriptor for url.
61
62 kwargs are passed on to LinkDef and include, in particular,
63 semantics, contentType, contentLength, description,
64 localSemantics, and contentQualifier.
65 """
66 if not "semantics" in kwargs:
67 kwargs["semantics"] = self.forSemantics
68 return LinkDef(self.pubDID, url, **kwargs)
69
70 def makeLinkFromFile(self, localPath, description, semantics=None,
71 service=None, contentType=None, suppressMissing=False,
72 localSemantics=None, contentQualifier=None):
73 """returns a LinkDef for a local file.
74
75 Arguments are as for LinkDef.fromFile, except you don't have
76 to pass in service if you're using the datalink service itself
77 to access the file; this method will try to find the service by
78 itself.
79 """
80 if service is None:
81 try:
82 service = inspect.currentframe().f_back.f_locals["self"].parent
83 except (KeyError, AttributeError):
84 raise base.StructureError("Cannot infer service for datalink"
85 " file link. Pass an appropriate service manually.")
86
87 if semantics is None:
88 semantics = self.forSemantics
89
90 return LinkDef.fromFile(localPath, description, semantics,
91 service=service, contentType=contentType,
92 suppressMissing=suppressMissing, localSemantics=localSemantics,
93 contentQualifier=contentQualifier)
94
95 @contextlib.contextmanager
96 def currentSemantics(self, sem):
97 """sets the default semantics for links and faults generated in
98 the controlled block to sem.
99 """
100 oldSemantics = self.forSemantics
101 self.forSemantics = sem
102 try:
103 yield
104 finally:
105 self.forSemantics = oldSemantics
106
107 def cleanup(self):
108 """this method is called at the end of a dlget run.
109
110 Use it to, for instance, close any files you still have open. By
111 default, it does nothing.
112 """
113
114
115 class ProductDescriptor(DatalinkDescriptorMixin):
116 """An encapsulation of information about some "product" (i.e., file).
117
118 This is basically equivalent to a line in the product table; the
119 arguments of the constructor are all available as same-named attributes.
120
121 It also has an attribute data defaulting to None. DataGenerators
122 set it, DataFilters potentially change it.
123
124 There is also a method cleanup() that is called at the end of dlget
125 processing; the default implementation does nothing, so there is no
126 need to up-call when you override it from here.
127
128 If you inherit from this class and you have a way to guess the
129 size of what the descriptor describes, override the estimateSize()
130 method. The default will return a file size if accessPath points
131 to an existing file, None otherwise.
132 """
133
134 def __init__(self, pubDID, accref, accessPath, mime,
135 owner=None, embargo=None, sourceTable=None, datalink=None,
136 preview=None, preview_mime=None):
137 self.pubDID = pubDID
138 self.accref, self.accessPath, self.mime = accref, accessPath, mime
139 self.owner, self.embargo, self.sourceTable = owner, embargo, sourceTable
140 self.preview, self.previewMime = preview, preview_mime
141
142 @classmethod
143 def fromAccref(cls, pubDID, accref, accrefPrefix=None, **moreKWs):
144 """returns a product descriptor for an access reference.
145
146 If an accrefPrefix is passed in, an AuthenticationFault (for want
147 of something better fitting) is returned when the accref doesn't
148 start with accrefPrefix.
149 """
150 if accrefPrefix and not accref.startswith(accrefPrefix):
151 return DatalinkFault.AuthenticationFault(pubDID,
152 "This Datalink service not available"
153 " with this pubDID", semantics="#this")
154
155 kwargs = products.RAccref(accref).productsRow
156 kwargs.update(moreKWs)
157 return cls(pubDID, **kwargs)
158
159 def estimateSize(self):
160 if isinstance(self.accessPath, str):
161 candPath = base.getConfig("inputsDir") / self.accessPath
162 try:
163 return os.path.getsize(candPath)
164 except:
165 # fall through to returning None
166 pass
167
168
169 class FITSProductDescriptor(ProductDescriptor):
170 """A SODA descriptor for FITS files.
171
172 On top of the normal product descriptor, this has an attribute hdr
173 containing a copy of the image header, and a method
174 changingAxis (see there).
175
176 There's also an attribute dataIsPristine that must be set to false
177 if changes have been made. The formatter will spit out the original
178 data otherwise, ignoring your changes.
179
180 Finally, there's a slices attribute provided explained in
181 soda#fits_doWCSCutout that can be used by data functions running before
182 it to do cutouts.
183
184 Append any files you have open during dlget processing to self.toClose.
185 The cleanup method makes sure they are closed before continuing.
186
187 The FITSProductDescriptor is constructed like a normal ProductDescriptor.
188 """
189
190 def __init__(self, *args, **kwargs):
191 self.toClose = []
192 qnd = kwargs.pop("qnd", True)
193 ProductDescriptor.__init__(self, *args, **kwargs)
194
195 self.imageExtind = 0
196
197 if qnd and self.imageExtind==0:
198 with open(base.getConfig("inputsDir") / self.accessPath, "rb") as f:
199 self.hdr = utils.readPrimaryHeaderQuick(f,
200 maxHeaderBlocks=100)
201
202 else:
203 hdus = pyfits.open(base.getConfig("inputsDir") / self.accessPath)
204 self.imageExtind = fitstools.fixImageExtind(
205 hdus, self.imageExtind)
206 self.hdr = hdus[self.imageExtind].header
207 hdus.close()
208
209 self.slices = []
210 self.dataIsPristine = True
211 self._axesTouched = set()
212
213 def changingAxis(self, axisIndex, parName):
214 """must be called before cutting out along axisIndex.
215
216 axIndex is a FITS (1-based) axis index axIndex, parName the name of the
217 parameter that causes the cutout.
218
219 This will simply return if nobody has called changingAxis with that index
220 before and raise a ValidationError otherwise. Data functions doing a cutout
221 must call this before doing so; if they don't the cutout will probably be
222 wrong when two conflicting constraints are given.
223 """
224 if axisIndex in self._axesTouched:
225 raise base.ValidationError("Attempt to cut out along axis %d that"
226 " has been modified before."%axisIndex, parName)
227 self._axesTouched.add(axisIndex)
228
229 def cleanup(self):
230 for closable in self.toClose:
231 closable.close()
232
233
234 class DLFITSProductDescriptor(FITSProductDescriptor):
235 """A SODA descriptor for FITS files with datalink product paths.
236
237 Use is as descClass in //soda#fits_genDesc when the product table
238 has a datalink as the product.
239 """
240 def __init__(self, *args, **kwargs):
241 kwargs["accessPath"] = str(
242 base.getConfig("inputsDir") / kwargs["accref"])
243 FITSProductDescriptor.__init__(self, *args, **kwargs)
244
245
246 def getFITSDescriptor(pubDID, accrefPrefix=None,
247 cls=FITSProductDescriptor, qnd=False):
248 """returns a datalink descriptor for a FITS file.
249
250 This is the implementation of fits_genDesc and should probably reused
251 when making more specialised descriptors.
252 """
253 try:
254 accref = rscdef.getAccrefFromStandardPubDID(pubDID)
255 except ValueError:
256 return DatalinkFault.NotFoundFault(pubDID,
257 "Not a pubDID from this site.")
258
259 return cls.fromAccref(pubDID, accref, accrefPrefix, qnd=qnd)
260
261
262 class _File(static.File):
263 """A nevow static.File with a pre-determined type.
264 """
265 def __init__(self, path, mediaType):
266 static.File.__init__(self, path)
267 self.type = mediaType
268 self.encoding = None
269
270
271 class _TemporaryFile(_File):
272 """A nevow resource that spits out a file and then deletes it.
273
274 This is a helper class for DataFunctions and DataFormatters, available
275 there as TemporaryFile.
276 """
277 def render(self, request):
278 request.notifyFinish().addBoth(
279 self._cleanup)
280 return _File.render(self, request)
281
282 def _cleanup(self, result):
283 self.remove()
284 return result
285
286
287 class DescriptorGenerator(rscdef.ProcApp):
288 """A procedure application for making product descriptors for PUBDIDs
289
290 Despite the name, a descriptor generator has to *return* (not yield)
291 a descriptor instance. While this could be anything, it is recommended
292 to derive custom classes from prodocols.datalink.ProductDescrpitor, which
293 exposes essentially the columns from DaCHS' product table as attributes.
294 This is what you get when you don't define a descriptor generator
295 in your datalink core.
296
297 Before writing your own, see if one of the predefined descriptor
298 generators work for you; see `Descriptor Generators`_ below.
299
300 The following names are available to the code:
301
302 * pubDID -- the pubDID to be resolved
303 * args -- all the arguments that came in from the web
304 (these should not usually be necessary for making the descriptor
305 and are completely unparsed at this point)
306 * FITSProductDescriptor -- the base class of FITS product descriptors
307 * DLFITSProductDescriptor -- the same, just for when the product table
308 has a datalink.
309 * ProductDescriptor -- a base class for your own custom descriptors
310 * DatalinkFault -- use this when flagging failures
311 * soda -- contents of the soda module for convenience
312
313 If you made your pubDID using the ``getStandardPubDID`` rowmaker function,
314 and you need no additional logic within the descriptor,
315 the default (//soda#fromStandardPubDID) should do.
316
317 If you need to derive custom descriptor classes, you can see the base
318 class under the name ProductDescriptor; there's also
319 FITSProductDescriptor and DatalinkFault in each proc's namespace.
320 If your Descriptor does not actually refer to something in the
321 product table, it is likely that you want to set the descriptor's
322 ``suppressAutoLinks`` attribute to True. This will stop DaCHS
323 from attempting to add automatic #this and #preview links.
324 """
325 name_ = "descriptorGenerator"
326 requiredType = "descriptorGenerator"
327 formalArgs = "pubDID, args"
328
329 additionalNamesForProcs = {
330 "FITSProductDescriptor": FITSProductDescriptor,
331 "DLFITSProductDescriptor": DLFITSProductDescriptor,
332 "ProductDescriptor": ProductDescriptor,
333 "getFITSDescriptor": getFITSDescriptor,
334 "DatalinkFault": DatalinkFault,
335 "soda": soda,
336 }
337
338
339 class LinkDef:
340 """a definition of a datalink related document.
341
342 These are constructed at least with:
343
344 - the pubDID (as a string)
345 - the access URL (as a string)
346
347 In addition, we accept the remaining column names from
348 `//datalink#dlresponse`_ as keyword arguments, except we use
349 camel case here, i.e.,
350 ``description``, ``semantics``, ``contentType``, ``contentLength``,
351 ``localSemantics``.
352
353 You usually do not want to construct LinkDefs directly. Use
354 the makeLink or makeLinkFromFile methods on descriptors instead.
355 Also, define semantics via the attribute on `element metaMaker`_
356 whenever you can; that will improve error messages.
357 """
358 def __init__(self, pubDID, accessURL,
359 serviceType=None,
360 errorMessage=None,
361 description=None,
362 semantics=DEFAULT_SEMANTICS,
363 contentType=None,
364 contentLength=None,
365 localSemantics=None,
366 contentQualifier=None):
367 ID = pubDID #noflake: used in locals()
368 del pubDID
369 self.dlRow = locals()
370
371 @classmethod
372 def fromFile(cls, localPath, description, semantics,
373 service, contentType=None, localSemantics=None,
374 contentQualifier=None,
375 suppressMissing=False):
376 """constructs a LinkDef based on a local file.
377
378 You must give localPath (which may be resdir-relative), description and
379 semantics are mandatory. ContentType and contentSize will normally be
380 determined by DaCHS.
381
382 You must also pass in the service used to retrieve the file. This
383 must allow the static renderer and have a staticData property. It should
384 normally be the datalink service itself, which in a metaMaker
385 is accessible as self.parent.parent. It is, however, legal
386 to reference other suitable services (use self.parent.rd.getById or
387 base.resolveCrossId)
388
389 If you pass suppressMissing=True, a link to a non-existing file
390 will be skipped rather than create a missing datalink.
391 """
392 baseDir = service.rd.resdir
393 localPath = os.path.join(baseDir, localPath)
394 pubDID = utils.stealVar("descriptor").pubDID
395 staticPath = os.path.join(baseDir,
396 service.getProperty("staticData"))
397
398 if not os.path.isfile(localPath):
399 if suppressMissing:
400 return None
401 else:
402 return DatalinkFault.NotFoundFault(pubDID, "No file"
403 " for linked item", semantics=semantics, description=description)
404 elif not os.access(localPath, os.R_OK):
405 return DatalinkFault.AutorizationFault(pubDID, "Linked"
406 " item not readable", semantics=semantics, description=description)
407
408 try:
409 svcPath = utils.getRelativePath(localPath, staticPath)
410 except ValueError:
411 return LinkDef(pubDID, errorMessage="FatalFault: Linked item"
412 " not accessible through the given service",
413 semantics=semantics, description=description,
414 localSemantics=localSemantics)
415
416 ext = os.path.splitext(localPath)[-1]
417 contentType = (contentType
418 or static.File.contentTypes.get(ext, "application/octet-stream"))
419
420 return cls(pubDID,
421 service.getURL("static")+"/"+svcPath,
422 description=description, semantics=semantics,
423 contentType=contentType,
424 contentLength=os.path.getsize(localPath),
425 localSemantics=localSemantics,
426 contentQualifier=contentQualifier)
427
428 def asDict(self):
429 """returns the link definition in a form suitable for ingestion
430 in //datalink#dlresponse.
431 """
432 return {
433 "ID": self.dlRow["ID"],
434 "access_url": self.dlRow["accessURL"],
435 "service_def": self.dlRow["serviceType"],
436 "error_message": self.dlRow["errorMessage"],
437 "description": self.dlRow["description"],
438 "semantics": self.dlRow["semantics"],
439 "content_type": self.dlRow["contentType"],
440 "content_length": self.dlRow["contentLength"],
441 "local_semantics": self.dlRow["localSemantics"],
442 "content_qualifier": self.dlRow["contentQualifier"]}
443
444
445 class ProcLinkDef:
446 """a definition of a datalink processing service other than self's dlget.
447
448 Whenever you datalink service allows a dlget, a descriptor for that
449 will be generated based on the keys returned by the metamaker. Sometimes,
450 you want to provide a second processing service within a single datalink
451 document. In that case, yield a ProcLinkDef objects constructed
452 with a dlget-allowing datalink service in its second argument. As usual
453 for LinkDefs, the first argument must be the DID for which to generate
454 the service.
455
456 The description of this link will be the description of that service.
457 """
458 def __init__(self, pubDID, dlSvc):
459 if (not isinstance(dlSvc, svcs.Service)
460 or not "dlget" in dlSvc.allowed):
461 raise base.StructureError("ProcLinkDef must be constructed"
462 " with a dlget-renderable service.")
463 self.pubDID = pubDID
464 self.svcId = None
465 self.description = base.getMetaText(dlSvc, "description",
466 default="Another interactive service on this dataset.")
467
468 # this is for stealing by adaptForRenderer
469 args = {"ID": [self.pubDID]} #noflake: for stealing
470 dlget = svcs.getRenderer("dlget")
471 dlgetCore = dlSvc.core.adaptForRenderer(
472 dlget, {"dbLimit": None})
473
474 self.serviceDescriptor = _ServiceDescriptor(
475 self.pubDID,
476 dlgetCore.inputKeys,
477 "dlget",
478 dlSvc)
479
480 def asDict(self):
481 """returns a datalink row for this service.
482
483 This is called by //datalink#make_response for the table row.
484 """
485 if self.svcId is None:
486 raise base.Error("You need to arrange for asVOT to be called first"
487 f" on this {self.__class__}.")
488 return {
489 "ID": self.pubDID,
490 "service_def": self.svcId,
491 "description": self.description,
492 "semantics": "#proc"}
493
494 def asVOT(self, ctx):
495 """returns a VOTable fragment for the service descriptor
496
497 This called by runForMeta. It currently constructs an actual
498 Datalink core for every pubDID, which is *relatively* expensive.
499 If you find your datalink service is prohibitively slow, we may
500 want to re-think this.
501 """
502 self.svcId = ctx.getOrMakeIdFor(
503 self.serviceDescriptor, suggestion="ext_svc")
504 return self.serviceDescriptor.asVOT(ctx)
505
506
507 class ExternalProcLinkDef:
508 """a description of a non-DaCHS processing service.
509
510 This results in a datalink #proc line with a service descriptor
511 that has:
512
513 * standardId and accessURL as global params (where standardID is optional)
514 * inputKeys as future members of the inputParams GROUP
515 * description and local_semantics as the respective fields in the
516 datalink table
517 * title for use in the descriptor block.
518 """
519 def __init__(self,
520 pubDID,
521 inputKeys,
522 accessURL,
523 title,
524 description,
525 localSemantics="",
526 standardId=None):
527 self.pubDID = pubDID
528 self.accessURL = accessURL
529 self.localSemantics = localSemantics
530 self.description = description
531
532 self.serviceDescriptor = _ExternalServiceDescriptor(
533 self.pubDID,
534 inputKeys,
535 accessURL,
536 "external service",
537 title,
538 self.description,
539 standardId)
540
541 def asDict(self):
542 """returns a datalink row for this service.
543
544 This is called by //datalink#make_response for the table row.
545 """
546 if self.svcId is None:
547 raise base.Error("You need to arrange for asVOT to be called first"
548 f" on this {self.__class__}.")
549 return {
550 "ID": self.pubDID,
551 "service_def": self.svcId,
552 "description": self.description,
553 "semantics": "#proc",
554 "local_semantics": self.localSemantics}
555
556 def asVOT(self, ctx):
557 """returns a VOTable fragment for the service descriptor
558
559 This called by runForMeta.
560 """
561 self.svcId = ctx.getOrMakeIdFor(
562 self.serviceDescriptor, suggestion="ext_svc")
563 return self.serviceDescriptor.asVOT(ctx)
564
565
566 class _SerialisableServiceDescriptor:
567 """something that implements the getVOT method for _XServiceDescriptor-s.
568 """
569 def asVOT(self, ctx, linkIdTo=None):
570 """returns VOTable stanxml for a description of this service.
571
572 This is a RESOURCE as required by Datalink.
573
574 linkIdTo is used to support data access descriptors embedded
575 in discovery queries. It is the id of the column containing
576 the identifiers. SSA can already provide this.
577 """
578 paramsByName, stcSpecs = {}, set()
579 for param in self.inputKeys:
580 paramsByName[param.name] = param
581 if param.stc:
582 stcSpecs.add(param.stc)
583
584 def getIdFor(colRef):
585 colRef.toParam = True
586 return ctx.getOrMakeIdFor(paramsByName[colRef.dest],
587 suggestion=colRef.dest)
588
589 res = V.RESOURCE(ID=ctx.getOrMakeIdFor(self, suggestion="proc_svc"),
590 name=self.name,
591 type="meta",
592 utype="adhoc:service")[
593 V.DESCRIPTION[self.description],
594 V.INFO(name="title", value=self.title),
595 [modelgroups.marshal_STC(ast, getIdFor)[0]
596 for ast in stcSpecs],
597 V.PARAM(arraysize="*", datatype="char",
598 name="accessURL", ucd="meta.ref.url",
599 value=self.accessURL)]
600
601 if self.standardId:
602 res[
603 V.PARAM(arraysize="*", datatype="char",
604 name="standardID", value=self.standardId)]
605
606 inputParams = V.GROUP(name="inputParams")
607 res = res[inputParams]
608
609 for ik in self.inputKeys:
610 param = ctx.addID(ik,
611 votablewrite.makeFieldFromColumn(ctx, V.PARAM, ik))
612
613 if linkIdTo and ik.name=="ID":
614 param = param(ref=linkIdTo)
615
616 if ik.hasProperty("defaultForForm"):
617 param[
618 V.LINK(action="rdf", content_role="#pre-set",
619 value=str(ik.getProperty("defaultForForm")))]
620 inputParams[param]
621
622 return res
623
624
625 class _ExternalServiceDescriptor(_SerialisableServiceDescriptor):
626 """A descriptor for a non-Datalink service.
627
628 These are for when there is no dlget renederer on the service or all
629 you have is a URL and some parameters.
630
631 See ExternalProcLinkDef for what this is constructed with.
632 """
633 def __init__(self,
634 pubDID,
635 inputKeys,
636 accessURL,
637 name,
638 title,
639 description,
640 standardId):
641 self.pubDID, self.inputKeys = pubDID, inputKeys,
642 self.accessURL, self.description = accessURL, description
643 self.title, self.name = title, name
644 self.standardId = standardId
645
646
647 class _ServiceDescriptor(_SerialisableServiceDescriptor):
648 """An internal descriptor for one of our services.
649
650 These are serialized into service resources in VOTables.
651 Basically, these collect input keys, a pubDID, as well as any other
652 data we might need in service definition.
653 """
654 def __init__(self, pubDID, inputKeys, rendName, dlSvc):
655 self.pubDID, self.inputKeys = pubDID, inputKeys
656 self.dlSvc, self.rendName = dlSvc, rendName
657 self.name = self.dlSvc.id
658
659 if self.pubDID:
660 # if we're fixed to a specific pubDID, reflect that in the ID
661 # field -- this is how clients know which dataset to pull
662 # from datalink documents.
663 for index, ik in enumerate(self.inputKeys):
664 if ik.name=="ID":
665 ik = ik.copy(None)
666 ik.set(pubDID)
667 self.inputKeys[index] = ik
668
669 self.standardId = base.getMetaText(self.dlSvc, "standardID", default=None)
670 if self.standardId is None:
671 self.standardId = {
672 "dlasync": ASYNC_STANDARD_ID,
673 "dlget": SYNC_STANDARD_ID}.get(rendName)
674
675 @property
676 def description(self):
677 return base.getMetaText(self.dlSvc,
678 "description",
679 default="An interactive service on this dataset.")
680
681 @property
682 def title(self):
683 return base.getMetaText(self.dlSvc,
684 "title",
685 default="Processing service with id {}".format(self.dlSvc.id))
686
687 @property
688 def accessURL(self):
689 # this is a property because we may not have an RD when the
690 # descriptor is constructed, and hence we want to defer this
691 # computation
692 return self.dlSvc.getURL(self.rendName)
693
694
695 class MetaMaker(rscdef.ProcApp):
696 """A procedure application that generates metadata for datalink services.
697
698 The code must be generators (i.e., use yield statements) producing either
699 svcs.InputKeys or protocols.datalink.LinkDef instances.
700
701 metaMaker see the data descriptor of the input data under the name
702 descriptor.
703
704 The data attribute of the descriptor is always None for metaMakers, so
705 you cannot use anything given there.
706
707 Within MetaMakers' code, you can access InputKey, Values, Option, and
708 LinkDef without qualification, and there's the MS function to build
709 structures. Hence, a metaMaker returning an InputKey could look like this::
710
711 <metaMaker>
712 <code>
713 yield MS(InputKey, name="format", type="text",
714 description="Output format desired",
715 values=MS(Values,
716 options=[MS(Option, content_=descriptor.mime),
717 MS(Option, content_="text/plain")]))
718 </code>
719 </metaMaker>
720
721 (of course, you should give more metadata -- ucds, better description,
722 etc) in production).
723
724 Note that InputKey-returning MetaMakers cannot rely
725 on descriptor.pubDID to actually have
726 a value; in particular SSA may construct cores to produce "direct"
727 processing datalink descriptors. When you need a pubDID, just return if
728 descriptor.pubDID is None.
729
730 Alternatively, yield link definitions, i.e., rows for the links response.
731 You will usually define a semantics attribute for the meta maker then
732 (this lets DaCHS use the right semantics in case something goes wrong),
733 and you will usually create links from the descriptor so the pubDID will
734 be right automatically::
735
736 <metaMaker semantics="#flat">
737 <code>
738 yield descriptor.makeLink(
739 "http://example.org/flats/master-flat.fits",
740 contentType="application/fits",
741 description="The master flat for this epoch",
742 contentLength=2048x2048*2)
743 </code>
744 </metaMaker>
745
746 It's ok to yield None; this will suppress a Datalink and is convenient
747 when some component further down figures out that a link doesn't exist
748 (e.g., because a file isn't there). Note that in many cases, it's
749 more helpful to client components to handle such situations by
750 yielding a DatalinkFault.NotFoundFault.
751
752 In addition to the usual names available to ProcApps, meta makers have:
753
754 - MS -- function to make DaCHS structures
755 - InputKey -- the class to make for input parameters
756 - Values -- the class to make for input parameters' values attributes
757 - Options -- used by Values
758 - LinkDef -- a class to define further links within datalink services.
759 - ProcLinkDef -- a class to reference dlget services outside of the current
760 service
761 - ExternalProcLinkDef -- a class to reference arbitrary services
762 (typically outside outside of the local DaCHS system).
763 - DatalinkFault -- a container of datalink error generators
764 - soda -- the soda module.
765 """
766 name_ = "metaMaker"
767 requiredType = "metaMaker"
768 formalArgs = "self, descriptor"
769
770 additionalNamesForProcs = {
771 "MS": base.makeStruct,
772 "InputKey": svcs.InputKey,
773 "Values": rscdef.Values,
774 "Option": rscdef.Option,
775 "LinkDef": LinkDef,
776 "ProcLinkDef": ProcLinkDef,
777 "ExternalProcLinkDef": ExternalProcLinkDef,
778 "DatalinkFault": DatalinkFault,
779 "soda": soda,
780 }
781
782 _semantics = base.UnicodeAttribute("semantics", default=DEFAULT_SEMANTICS,
783 description="For link-generating metaMakers, the semantics"
784 " makeLink or makeLinkFromFile will use unless given something else."
785 " This is also what will be used if the meta maker exceptions out."
786 " Note that the default is not good and is only set for backwards"
787 " compatibility. You should override this.",
788 copyable=True)
789
790
791 class DataFunction(rscdef.ProcApp):
792 """A procedure application that generates or modifies data in a processed
793 data service.
794
795 All these operate on the data attribute of the product descriptor.
796 The first data function plays a special role: It *must* set the data
797 attribute (or raise some appropriate exception), or a server error will
798 be returned to the client.
799
800 What is returned depends on the service, but typically it's going to
801 be a table or products.*Product instance.
802
803 Data functions can shortcut if it's evident that further data functions
804 can only mess up (i.e., if the do something bad with the data attribute);
805 you should not shortcut if you just *think* it makes no sense to
806 further process your output.
807
808 To shortcut, raise either of FormatNow (falls though to the formatter,
809 which is usually less useful) or DeliverNow (directly returns the
810 data attribute; this can be used to return arbitrary chunks of data).
811
812 The following names are available to the code:
813
814 * descriptor -- whatever the DescriptorGenerator returned
815 * args -- all the arguments that came in from the web.
816
817 In addition to the usual names available to ProcApps, data functions have:
818
819 * FormatNow -- exception to raise to go directly to the formatter
820 * DeliverNow -- exception to raise to skip all further formatting
821 and just deliver what's currently in descriptor.data
822 * File(path, type) -- if you just want to return a file on disk, pass
823 its path and media type to File and assign the result to
824 descriptor.data.
825 * TemporaryFile(path,type) -- as File, but the disk file is
826 unlinked after use
827 * makeData -- the rsc.makeData function
828 * soda -- the protocols.soda module
829 * RemoteProduct(url) -- 301-redirects to URL when rendered
830 """
831 name_ = "dataFunction"
832 requiredType = "dataFunction"
833 formalArgs = "descriptor, args"
834
835 additionalNamesForProcs = {
836 "FormatNow": FormatNow,
837 "DeliverNow": DeliverNow,
838 "File": _File,
839 "TemporaryFile": _TemporaryFile,
840 "makeData": rsc.makeData,
841 "soda": soda,
842 "DataFromURL": products.RemoteProduct.fromURL,
843 }
844
845
846 class DataFormatter(rscdef.ProcApp):
847 """A procedure application that renders data in a processed service.
848
849 These play the role of the renderer, which for datalink is usually
850 trivial. They are supposed to take descriptor.data and return
851 a pair of (mime-type, bytes), which is understood by most renderers.
852
853 When no dataFormatter is given for a core, it will return descriptor.data
854 directly. This can work with the datalink renderer itself if
855 descriptor.data will work as a nevow resource (i.e., has a renderHTTP
856 method, as our usual products do). Consider, though, that renderHTTP
857 runs in the main event loop and thus most not block for extended
858 periods of time.
859
860 The following names are available to the code:
861 * descriptor -- whatever the DescriptorGenerator returned
862 * args -- all the arguments that came in from the web.
863
864 In addition to the usual names available to ProcApps, data formatters have:
865
866 * Page -- base class for resources with renderHTTP methods.
867 * IRequest -- the nevow interface to make Request objects with.
868 * File(path, type) -- if you just want to return a file on disk, pass
869 its path and media type to File and return the result.
870 * TemporaryFile(path, type) -- as File, but the disk file is unlinked
871 after use
872 * soda -- the protocols.soda module
873 """
874 name_ = "dataFormatter"
875 requiredType = "dataFormatter"
876 formalArgs = "descriptor, args"
877
878 additionalNamesForProcs = {
879 "Page": nevowc.TemplatedPage,
880 "IRequest": lambda arg:arg, # compatibility wrapper
881 "File": _File,
882 "TemporaryFile": _TemporaryFile,
883 "soda": soda,
884 }
885
886
887 class DatalinkCoreBase(svcs.Core, base.ExpansionDelegator):
888 """Basic functionality for datalink cores.
889
890 This is pulled out of the datalink core proper as it is used without
891 the complicated service interface sometimes, e.g., by SSAP.
892 """
893
894 _descriptorGenerator = base.StructAttribute("descriptorGenerator",
895 default=base.NotGiven,
896 childFactory=DescriptorGenerator,
897 description="Code that takes a PUBDID and turns it into a"
898 " product descriptor instance. If not given,"
899 " //soda#fromStandardPubDID will be used.",
900 copyable=True)
901
902 _metaMakers = base.StructListAttribute("metaMakers",
903 childFactory=MetaMaker,
904 description="Code that takes a data descriptor and either"
905 " updates input key options or yields related data.",
906 copyable=True)
907
908 _dataFunctions = base.StructListAttribute("dataFunctions",
909 childFactory=DataFunction,
910 description="Code that generates of processes data for this"
911 " core. The first of these plays a special role in that it"
912 " must set descriptor.data, the others need not do anything"
913 " at all.",
914 copyable=True)
915
916 _dataFormatter = base.StructAttribute("dataFormatter",
917 default=base.NotGiven,
918 childFactory=DataFormatter,
919 description="Code that turns descriptor.data into a nevow resource"
920 " or a mime, content pair. If not given, the renderer will be"
921 " returned descriptor.data itself (which will probably not usually"
922 " work).",
923 copyable=True)
924
925 _inputKeys = rscdef.ColumnListAttribute("inputKeys",
926 childFactory=svcs.InputKey,
927 description="A parameter to one of the proc apps (data functions,"
928 " formatters) active in this datalink core; no specific relation"
929 " between input keys and procApps is supposed; all procApps are passed"
930 " all arguments. Conventionally, you will write the input keys in"
931 " front of the proc apps that interpret them.",
932 copyable=True)
933
934 # This tells the context grammar to fail if someone tries to pass
935 # in parameters we don't have input keys for.
936 rejectExtras = True
937
938 def completeElement(self, ctx):
939 if self.descriptorGenerator is base.NotGiven:
940 self.descriptorGenerator = MS(DescriptorGenerator,
941 procDef=base.resolveCrossId("//soda#fromStandardPubDID"))
942
943 if self.dataFormatter is base.NotGiven:
944 self.dataFormatter = MS(DataFormatter,
945 procDef=base.caches.getRD("//soda").getById("trivialFormatter"))
946
947 self.inputKeys.append(MS(svcs.InputKey, name="ID", type="text",
948 ucd="meta.id;meta.main",
949 multiplicity="multiple",
950 std=True,
951 description="The publisher DID of the dataset of interest"))
952
953 if self.inputTable is base.NotGiven:
954 self.inputTable = MS(svcs.InputTD, inputKeys=self.inputKeys)
955
956 # this is a cheat for service.getTableSet to pick up the datalink
957 # table. If we fix this for TAP, we should fix it here, too.
958 self.queriedTable = base.caches.getRD("//datalink").getById(
959 "dlresponse")
960
961 super().completeElement(ctx)
962
963 def getMetaForDescriptor(self, descriptor):
964 """returns a pair of linkDefs, inputKeys for a datalink descriptor
965 and this core.
966 """
967 linkDefs, inputKeys, errors = [], self.inputKeys[:], []
968
969 for metaMaker in self.metaMakers:
970 with descriptor.currentSemantics(metaMaker.semantics):
971 try:
972 for item in metaMaker.compile(self)(self, descriptor):
973 if isinstance(item, (LinkDef, ProcLinkDef, ExternalProcLinkDef)):
974 linkDefs.append(item)
975 elif isinstance(item, DatalinkFault):
976 errors.append(item)
977 elif item is None:
978 pass
979 else:
980 inputKeys.append(self.adopt(item))
981 except Exception as ex:
982 if base.DEBUG:
983 base.ui.notifyError("Error in datalink meta generator %s: %s"%(
984 metaMaker, repr(ex)))
985 base.ui.notifyError("Failing source: \n%s"%metaMaker.getFuncCode())
986 errors.append(DatalinkFault.Fault(descriptor.pubDID,
987 "Unexpected failure while creating"
988 " datalink: %s"%utils.safe_str(ex),
989 semantics=descriptor.forSemantics))
990
991 return linkDefs, inputKeys, errors
992
993 def _iterAutoLinks(self, descriptor, service):
994 """yields automatic links for descriptor.
995
996 That's #that and #preview unless some special conditions apply.
997 """
998 if (not isinstance(descriptor, ProductDescriptor)
999 or hasattr(descriptor, "suppressAutoLinks")):
1000 return
1001
1002 # if the accref is a datalink document, go through dlget itself.
1003 if descriptor.mime=="application/x-votable+xml;content=datalink":
1004 if isinstance(descriptor, DLFITSProductDescriptor):
1005 mediaType = "application/fits"
1006 else:
1007 mediaType = formats.guessMediaType(descriptor.accref),
1008 yield LinkDef(descriptor.pubDID,
1009 service.getURL("dlget")+"?ID=%s"%urllib.parse.quote(
1010 descriptor.pubDID),
1011 description="The full dataset.",
1012 contentType=mediaType,
1013 contentLength=descriptor.estimateSize(),
1014 contentQualifier=getattr(descriptor, "contentQualifier", None),
1015 semantics="#this")
1016
1017 else:
1018 yield LinkDef(descriptor.pubDID,
1019 products.makeProductLink(descriptor.accref),
1020 description="The full dataset.",
1021 contentType=descriptor.mime,
1022 contentLength=descriptor.estimateSize(),
1023 contentQualifier=getattr(descriptor, "contentQualifier", None),
1024 semantics="#this")
1025
1026 if getattr(descriptor, "preview", None):
1027 if descriptor.preview.startswith("http"):
1028 # deliver literal links directly
1029 previewLink = descriptor.preview
1030
1031 else:
1032 # It's either AUTO or a local path; in both cases, let
1033 # the products infrastructure worry about it.
1034 previewLink = products.makeProductLink(
1035 products.RAccref(descriptor.accref,
1036 inputDict={"preview": True}))
1037
1038 yield LinkDef(descriptor.pubDID,
1039 previewLink,
1040 description="A preview for the dataset.",
1041 contentType=descriptor.previewMime,
1042 semantics="#preview")
1043
1044 def getDatalinksResource(self, ctx, service):
1045 """returns a VOTable RESOURCE element with the data links.
1046
1047 This does not contain the actual service definition elements, but it
1048 does contain references to them.
1049
1050 You must pass in a VOTable context object ctx (for the management
1051 of ids). If this is the entire content of the VOTable, use
1052 votablewrite.VOTableContext() there.
1053 """
1054 internalLinks = []
1055
1056 internalLinks.extend(
1057 LinkDef(
1058 s.pubDID,
1059 None,
1060 serviceType=ctx.getOrMakeIdFor(s),
1061 description=s.description,
1062 semantics="#proc")
1063 for s in self.datalinkEndpoints)
1064
1065 # for all descriptors that are products, make a full dataset
1066 # available through the data access, possibly also adding a preview.
1067 for d in self.descriptors:
1068 for link in self._iterAutoLinks(d, service):
1069 internalLinks.append(link)
1070
1071 data = rsc.makeData(
1072 base.caches.getRD("//datalink").getById("make_response"),
1073 forceSource=self.datalinkLinks+internalLinks+self.errors)
1074 data.setMeta("_type", "results")
1075 data.contributingMetaCarriers.append(service)
1076
1077 return votablewrite.makeResource(
1078 votablewrite.VOTableContext(tablecoding="td"),
1079 data)
1080
1081
1082 class DatalinkCore(DatalinkCoreBase):
1083 """A core for processing datalink and processed data requests.
1084
1085 The input table of this core is dynamically generated from its
1086 metaMakers; it makes no sense at all to try and override it.
1087
1088 See `Datalink and SODA`_ for more information.
1089
1090 In contrast to "normal" cores, one of these is made (and destroyed)
1091 for each datalink request coming in. This is because the interface
1092 of a datalink service depends on the request's value(s) of ID.
1093
1094 The datalink core can produce both its own metadata and data generated.
1095 It is the renderer's job to tell them apart.
1096 """
1097 name_ = "datalinkCore"
1098
1099 datalinkType = "application/x-votable+xml;content=datalink"
1100
1101 overflowed = False
1102
1103 workerSystem = dlasync.DL_WORKER
1104
1105 # the core will be specially and non-cacheably adapted for these
1106 # renderers (ssap.xml is in here for legacy getData):
1107 datalinkAdaptingRenderers = frozenset([
1108 "form", "dlget", "dlmeta", "dlasync", "ssap.xml"])
1109
1110 def _getPubDIDs(self, args):
1111 """returns a list of pubDIDs from args["ID"].
1112
1113 args is supposed to be a nevow request.args-like dict, where the PubDIDs
1114 are taken from the ID parameter. If it's atomic, it'll be expanded into
1115 a list. If it's not present, a ValidationError will be raised.
1116 """
1117 pubDIDs = args.get("ID")
1118 if not pubDIDs:
1119 pubDIDs = []
1120 elif not isinstance(pubDIDs, list):
1121 pubDIDs = [pubDIDs]
1122 return pubDIDs
1123
1124 def adaptForDescriptors(self, renderer, descriptors, maxRec):
1125 """returns a core for renderer and a sequence of ProductDescriptors.
1126
1127 This method is mainly for helping adaptForRenderer. Do read the
1128 docstring there.
1129 """
1130 try:
1131 allowedForSvc = set(utils.stealVar("allowedRendsForStealing"))
1132 except ValueError:
1133 allowedForSvc = []
1134
1135 overflowed = False
1136 linkDefs, endpoints, errors = [], [], []
1137 for curInd, descriptor in enumerate(descriptors):
1138 if isinstance(descriptor, DatalinkFault):
1139 errors.append(descriptor)
1140
1141 else:
1142 lds, inputKeys, lerrs = self.getMetaForDescriptor(descriptor)
1143 linkDefs.extend(lds)
1144 errors.extend(lerrs)
1145
1146 # ssap expects the first renderer here to be dlget, so don't
1147 # remove it or move it back; also: only declare services
1148 # if they accept more than just ID; with just ID, it's obviously
1149 # just a bytestream generator for #this rather than a proper
1150 # service.
1151 for rendName in ["dlget", "dlasync"]:
1152 if len(inputKeys)>1 and rendName in allowedForSvc:
1153 endpoints.append(
1154 _ServiceDescriptor(
1155 descriptor.pubDID,
1156 inputKeys,
1157 rendName,
1158 self.parent))
1159
1160 if (renderer.name=="dlmeta"
1161 and maxRec is not None
1162 and len(linkDefs)+len(errors)>=maxRec):
1163 descriptors[curInd+1:] = []
1164 overflowed = True
1165 break
1166
1167 # dispatch on whether we're making metadata (case 1) or actual
1168 # data (case 2)
1169 inputKeys = self.inputKeys[:]
1170 if renderer.name=="dlmeta":
1171 pass # RESPONSEFORMAT and friends added through pql#DALIPars
1172
1173 else:
1174 # in dlget, we don't actually know what to do with multiple
1175 # descriptors. But we will fault out if the last (and usually
1176 # only one) has a problem.
1177 if not descriptors:
1178 raise base.ValidationError("ID is mandatory with dlget",
1179 "ID")
1180 # If there are multiple endpoints, we take the parameters from
1181 # the last one. If there are none, we keep the ID of the
1182 # main service interface.
1183 if endpoints:
1184 inputKeys = endpoints[-1].inputKeys
1185 if isinstance(descriptors[-1], DatalinkFault):
1186 descriptors[-1].raiseException()
1187
1188 res = self.change(inputTable=MS(svcs.InputTD,
1189 inputKeys=inputKeys, exclusive=True),
1190 inputKeys=inputKeys)
1191
1192 # again dispatch on meta or data, this time as regards what to run.
1193 if renderer.name=="dlmeta":
1194 res.run = res.runForMeta
1195 else:
1196 res.run = res.runForData
1197
1198 res.nocache = True
1199 res.datalinkLinks = linkDefs
1200 res.datalinkEndpoints = endpoints
1201 res.descriptors = descriptors
1202 res.errors = errors
1203 res.overflowed = overflowed
1204 return res
1205
1206 def adaptForRenderer(self, renderer, queryMeta):
1207 """returns a core for a specific product.
1208
1209 The ugly thing about datalink in DaCHS' architecture is that its
1210 interface (in terms of, e.g., inputKeys' values children) depends
1211 on the arguments themselves, specifically the pubDID.
1212
1213 The workaround is to abuse the renderer-specific getCoreFor,
1214 ignore the renderer and instead steal an "args" variable from
1215 somewhere upstack. Nasty, but for now an acceptable solution.
1216
1217 It is particularly important to never let service cache the
1218 cores returned for the dl* renderers; hence to "nocache" magic.
1219
1220 This tries to generate all datalink-relevant metadata in one go
1221 and avoid calling the descriptorGenerator(s) more than once per
1222 pubDID. It therefore adds datalinkLinks, datalinkEndpoints,
1223 and descriptors attributes. These are used later
1224 in either metadata generation or data processing.
1225
1226 An additional complication is MAXREC; when adaptForDescriptors
1227 will crop the descriptor list if more than MAXREC links (incl.
1228 errors) are generated if the renderer is dlmeta. On dlget,
1229 MAXREC is ignored; we don't really do multi-ID dlget right
1230 now, anyway.
1231
1232 The latter will in general use only the last pubDID passed in.
1233 Therefore, this last pubDID determines the service interface
1234 for now. Perhaps we should be joining the inputKeys in some way,
1235 though, e.g., if we want to allow retrieving multiple datasets
1236 in a tar file? Or to re-use the same service for all pubdids?
1237 """
1238 # if we're not speaking real datalink, return right away (this will
1239 # be cached, so this must never happen for actual data)
1240 if not renderer.name in self.datalinkAdaptingRenderers:
1241 return self
1242
1243 try:
1244 args = utils.stealVar("args")
1245 if not isinstance(args, dict):
1246 # again, we're not being called in a context with a pubdid
1247 raise ValueError("No pubdid")
1248 args = utils.CaseSemisensitiveDict(args)
1249 except ValueError:
1250 # no arguments found: decide later on whether to fault out.
1251 args = {"ID": []}
1252
1253 pubDIDs = self._getPubDIDs(args)
1254 descGen = self.descriptorGenerator.compile(self)
1255 descriptors = []
1256 for pubDID in pubDIDs:
1257 try:
1258 desc = descGen(pubDID, args)
1259 if desc is None:
1260 raise base.NotFoundError(pubDID, "dataset",
1261 "this site's data holdings")
1262
1263 if isinstance(desc, DatalinkFault):
1264 # fix non-informational semantics to #this, because
1265 # that's what making a descriptor is almost always about.
1266 if desc.semantics==soda.DEFAULT_SEMANTICS:
1267 desc.semantics = "#this"
1268
1269 descriptors.append(desc)
1270 except svcs.RedirectBase:
1271 # let through redirects even for dlmeta; these are rendered
1272 # further up in the call chain.
1273 raise
1274
1275 except Exception as ex:
1276 # if we're dlget, just let exceptions through (e.g., authentication),
1277 # also with a view to pushing out useful error messages.
1278 if renderer.name!="dlmeta":
1279 raise
1280 else:
1281 # In dlmeta, convert to fault rows.
1282 if isinstance(ex, base.NotFoundError):
1283 descriptors.append(DatalinkFault.NotFoundFault(pubDID,
1284 utils.safe_str(ex), semantics="#this"))
1285 else:
1286 if base.DEBUG:
1287 base.ui.notifyError("Error in datalink descriptor generator: %s"%
1288 utils.safe_str(ex))
1289 descriptors.append(DatalinkFault.Fault(pubDID,
1290 utils.safe_str(ex), semantics="#this"))
1291
1292 return self.adaptForDescriptors(
1293 renderer, descriptors, queryMeta["dbLimit"])
1294
1295 def _iterAccessResources(self, ctx, service):
1296 """iterates over the VOTable RESOURCE elements necessary for
1297 the datalink rows produced by service.
1298 """
1299 for dlSvc in self.datalinkEndpoints:
1300 yield dlSvc.asVOT(ctx)
1301
1302 for linkDef in self.datalinkLinks:
1303 # normal LinkDefs can also contribute VOTable material directly;
1304 # presumably, that'll always be RESOURCE blocks of dlget services,
1305 # but who knows: perhaps we'll one day want to return an extra
1306 # info or something?
1307 if hasattr(linkDef, "asVOT"):
1308 yield linkDef.asVOT(ctx)
1309
1310 def runForMeta(self, service, inputTable, queryMeta):
1311 """returns a rendered VOTable containing the datalinks.
1312 """
1313 try:
1314 ctx = votablewrite.VOTableContext(tablecoding="td")
1315
1316 # we'll need to serialise the access resources first, as ctx has to
1317 # produce their id-s before their table rows are produced.
1318 accessResources = list(
1319 self._iterAccessResources(ctx, service))
1320
1321 dlres = self.getDatalinksResource(ctx, service)
1322
1323 if self.overflowed:
1324 dlres[V.INFO(name="QUERY_STATUS", value="OVERFLOW")[
1325 "Results cropped after hitting the MAXREC you passed in."]]
1326
1327 else:
1328 dlres[V.INFO(name="QUERY_STATUS", value="OK")]
1329
1330 dlres[V.INFO(name="standardID",
1331 value=LINKS_STANDARD_ID)[
1332 "Written by DaCHS %s %s"%(
1333 base.getVersion(), self.__class__.__name__)],
1334 V.INFO(name="request", value=queryMeta["requestURI"])[
1335 "Request string that produced this VOTable"]
1336 if "requestURI" in queryMeta else None]
1337
1338 vot = V.VOTABLE[dlres, accessResources]
1339
1340 if "text/html" in queryMeta["accept"]:
1341 # we believe it's a web browser; let it do stylesheet magic
1342 destMime = "text/xml"
1343 else:
1344 destMime = self.datalinkType
1345
1346 destMime = str(inputTable.getParam("responseformat") or destMime)
1347 if destMime=="votable":
1348 destMime = self.datalinkType
1349
1350 res = (destMime, b"<?xml-stylesheet href='/static/xsl/"
1351 b"datalink-to-html.xsl' type='text/xsl'?>"+vot.render())
1352 return res
1353 finally:
1354 self.finalize()
1355
1356 def runForData(self, service, inputTable, queryMeta):
1357 """returns a data set processed according to inputTable's parameters.
1358 """
1359 try:
1360 args = inputTable.getParamDict()
1361 if not self.dataFunctions:
1362 raise base.DataError("This datalink service cannot process data")
1363
1364 descriptor = self.descriptors[-1]
1365
1366 for func in self.dataFunctions:
1367 try:
1368 func.compile(self)(descriptor, args)
1369 if descriptor.data is None:
1370 raise base.ReportableError(
1371 "Internal Error: a first data function did not create data.")
1372 except FormatNow:
1373 break
1374 except DeliverNow:
1375 return descriptor.data
1376 except Exception as exc:
1377 base.ui.notifyError(f"Data function {func} failed ({exc}).")
1378 raise
1379
1380 res = self.dataFormatter.compile(self)(descriptor, args)
1381 return res
1382 finally:
1383 self.descriptors[-1].cleanup()
1384 self.finalize()
1385
1386 def finalize(self):
1387 """breaks circular references to make the garbage collector's job
1388 easier.
1389
1390 The core will no longer function once this has been called.
1391 """
1392 utils.forgetMemoized(self)
1393 for proc in itertools.chain(self.metaMakers, self.dataFunctions):
1394 utils.forgetMemoized(proc)
1395 utils.forgetMemoized(self.descriptorGenerator)
1396 if self.dataFormatter:
1397 utils.forgetMemoized(self.dataFormatter)
1398 self.breakCircles()
1399 self.run = None
1400
1401
1402 def makeDatalinkServiceDescriptor(ctx, service, tableDef, columnName):
1403 """returns a datalink descriptor for a datalink (dlmeta) service).
1404
1405 What's returned is gavo.votable elements.
1406
1407 ctx is a votablewrite VOTableContext that manages the IDs of the elements
1408 involved, service is the datalink service as a svc.Service instance,
1409 tableDef is the rscdef.TableDef instance with the rows the datalink service
1410 operates on, and columnName names the column within table to take
1411 the datalink's ID parameter from.
1412 """
1413 return V.RESOURCE(type="meta", utype="adhoc:service", name=service.id)[
1414 V.DESCRIPTION[base.getMetaText(service, "description",
1415 default="A Datalink service to retrieve the data set"
1416 " as well as additional related files, plus possibly services"
1417 " for server-side processing.", propagate=False)],
1418 V.PARAM(name="standardID", datatype="char", arraysize="*",
1419 value=LINKS_STANDARD_ID),
1420 V.PARAM(name="accessURL", datatype="char", arraysize="*",
1421 value=service.getURL("dlmeta")),
1422 V.GROUP(name="inputParams")[
1423 V.PARAM(name="ID", datatype="char", arraysize="*",
1424 ref=ctx.getOrMakeIdFor(
1425 tableDef.getColumnByName(columnName), suggestion=columnName),
1426 ucd="meta.id;meta.main")]]