Debian Codegraph @

gavo/base/metavalidation.py

raw
1 """
2 Meta information validation.
3
4 The idea is that you define certain assertions about the meta information
5 of a given object type. Defined assertions are
6
7 - MetaExists -- a key is present
8 - MetaIsAtomic -- a key is present and a "leaf", i.e., has a single value
9 - MetaAtomicExistsOnSelf -- a key is present even without meta inheritance,
10 and has a single value
11 - MetaValueInVocabulary -- the value of a meta item is in an IVOA
12 vocabulary.
13
14 Validators are usually built using model descriptions. These are enumerations
15 of meta keys, separated by commas, with an optional code in parenteses.
16 Whitespace is ignored. Codes allowed in parens are:
17
18 - empty (default): plain existence
19 - !: atomic existence on self
20 - 1: atomic existence
21 - ?: optional (this only makes sense with other constraints, as
22 any meta value is allowed on anything
23 - voc:vocname: all values must come from the IVOA vocabulary
24 vocname.
25
26 Multiple assertions are separated by whitespace.
27
28 An example for a valid model description:
29 "publisher.name,creator.email(), identifier (!), dateUpdated(1)"
30
31 These model descriptions can come in metaModel attributes of structures.
32 If they are, you can use the validateStructure function below to validate
33 an entire structure tree.
34 """
35
36 #c Copyright 2008-2025, the GAVO project <[email protected]>
37 #c
38 #c This program is free software, covered by the GNU GPL. See the
39 #c COPYING file in the source distribution.
40
41
42 import functools
43
44 from gavo import utils
45 from gavo.base import meta
46
47 from gavo.utils.dachstypes import (cast,
48 Optional, Sequence, Structure, Vocabulary)
49
50
51 class MetaValidationError(meta.MetaError):
52 def __init__(self, carrier: meta.MetaMixin, failures: Sequence[str]):
53 self.pos = getattr(carrier, "getSourcePosition", lambda: None)()
54 self.failures = failures
55 if hasattr(carrier, "id") and carrier.id:
56 self.carrierRepr = carrier.id
57 else:
58 self.carrierRepr = "%s item"%carrier.__class__.__name__
59 meta.MetaError.__init__(self, "Meta structure on %s did not validate"%
60 self.carrierRepr, carrier)
61
62 def __str__(self) -> str:
63 return "Meta structure on %s (within %s) did not validate: %s"%(
64 self.carrierRepr, self.pos, ", ".join(self.failures))
65
66
67 class MetaAssertion:
68 """An assertion about the meta content of an object.
69
70 You must override the C{check} method.
71 """
72 def __init__(self, key: str):
73 self.key = key
74
75 def check(self, metaCarrier: meta.MetaMixin) -> Optional[str]:
76 """returns None if the assertion is true, a user-displayable string of
77 what failed otherwise.
78
79 This must be overridden in derived classes.
80 @param metaCarrier: an object mixing in L{MetaMixin}.
81 """
82
83 return f"Null assertion on {self.key} always fails"
84
85
86 class MetaExists(MetaAssertion):
87 """An assertion that a meta item is present for key in whatever form.
88 """
89 def check(self, metaCarrier):
90 if metaCarrier.getMeta(self.key) is None:
91 return "Meta key %s missing"%self.key
92
93
94 class MetaIsAtomic(MetaAssertion):
95 """An assertion that a meta item is present and contains a single value
96 only.
97 """
98 propagate = True
99 def check(self, metaCarrier):
100 val = metaCarrier.getMeta(self.key, propagate=self.propagate)
101 if val is None:
102 return "Meta key %s missing"%self.key
103 if len(val.children)!=1:
104 return "Meta key %s is not atomic"%self.key
105
106
107 class MetaAtomicExistsOnSelf(MetaIsAtomic):
108 """An assertion that a meta item is present and unique for key on
109 metaCarrier itself.
110 """
111 propagate = False
112
113
114 class NullAssertion(MetaAssertion):
115 """An assertion that always succeeds.
116
117 This is for implementation convenience.
118 """
119 def check(self, metaCarrier):
120 return None
121
122
123 class MetaValueInVocabulary(MetaAssertion):
124 def __init__(self, key: str, vocName: str):
125 self._vocName = vocName
126 MetaAssertion.__init__(self, key)
127
128 @functools.cache
129 def getVocabulary(self) -> Vocabulary:
130 from gavo.protocols import vocabularies
131 return vocabularies.get_vocabulary(self._vocName)
132
133 def check(self, metaCarrier: meta.MetaMixin) -> Optional[str]:
134 voc = self.getVocabulary()
135 for val in metaCarrier.iterMeta(self.key, propagate=True):
136 if str(val) not in voc["terms"]:
137 return (f"{self.key} meta only admits values from {self._vocName}"
138 f", but '{val}' is not in there.")
139 return None
140
141
142 class MetaValidator:
143 """A metadata model that can verify objects of compliance.
144
145 The model is quite simple: it's a sequence of MetaAssertions.
146 The validate(metaCarrier) -> None method raises a MetaNotValid
147 exception with all failed assertions in its failedAssertions
148 attribute.
149 """
150 def __init__(self, model: Sequence[MetaAssertion]):
151 self.model = model
152
153 def validate(self, metaCarrier: meta.MetaMixin) -> None:
154 failures = [msg for msg in (
155 ass.check(metaCarrier) for ass in self.model) if msg]
156 if failures:
157 raise MetaValidationError(metaCarrier, failures)
158
159
160 _assertionCodes = {
161 "": MetaExists,
162 '!': MetaAtomicExistsOnSelf,
163 '1': MetaIsAtomic,
164 '?': NullAssertion,
165 }
166
167
168 @functools.lru_cache(1)
169 def _getModelGrammar() -> utils.ParserElement:
170 from gavo.utils.parsetricks import (Literal, Optional, StringEnd, Suppress,
171 Word, ZeroOrMore, alphas, pyparsingWhitechars, Regex)
172
173 with pyparsingWhitechars(" \t"):
174 metaKey = Word(alphas+"._")
175 vocSpec = Regex("voc:[a-z/_-]+")
176 modChar = Literal('!') | '1' | '?'
177 modifier = (Suppress('(')
178 + Optional(modChar)("mod")
179 + Optional(vocSpec)("voc")
180 + Suppress(')'))
181 assertion = metaKey("key")+Optional(modifier)
182 model = assertion + ZeroOrMore(
183 Suppress(',') + assertion ) + StringEnd()
184
185 def _buildAssertions(s, p, toks):
186 key = str(toks["key"])
187 mod = str(toks.get("mod", ""))
188
189 assertions = [_assertionCodes[mod](key)]
190
191 voc = str(toks.get("voc", ""))
192 if voc:
193 assertions.append(MetaValueInVocabulary(key, voc[4:]))
194
195 return assertions
196
197 assertion.addParseAction(_buildAssertions)
198 model.addParseAction(lambda s,p,toks: MetaValidator(toks))
199 return model
200
201
202 def parseModel(modelDescr: str) -> utils.ParserElement:
203 """returns a MetaValidator for a model description.
204
205 model descriptions are covered in the module docstring.
206 """
207 return utils.pyparseString(_getModelGrammar(), modelDescr)[0]
208
209
210 def _validateMetaCarrier(metaCarrier: meta.MetaMixin) -> None:
211 """helps _validateStructNode.
212 """
213 if hasattr(metaCarrier.__class__, "metaModel"):
214 metaModel = metaCarrier.__class__.metaModel
215 if metaModel is None:
216 return
217 if isinstance(metaModel, str):
218 try:
219 metaCarrier.__class__.metaModel = parseModel(metaModel)
220 except utils.ParseException as msg:
221 raise utils.StructureError(
222 f"Invalid meta model on {metaCarrier.__class__.__name__}:"
223 f" {msg}")
224 metaModel = metaCarrier.__class__.metaModel
225 metaModel.validate(metaCarrier)
226
227
228 def _validateStructNode(aStruct: Structure) -> None:
229 """helps _validateStructure.
230 """
231 try:
232 _validateMetaCarrier(cast(meta.MetaMixin, aStruct))
233
234 if hasattr(aStruct, "getAllMetaPairs"):
235 for key, value in aStruct.getAllMetaPairs():
236 _validateMetaCarrier(value)
237
238 for s in aStruct.iterChildren():
239 if s:
240 _validateStructNode(s)
241 except MetaValidationError as exc:
242 if getattr(exc, "pos", None) is None:
243 exc.pos = aStruct.getSourcePosition()
244 raise
245
246
247 def validateStructure(aStruct: Structure) -> None:
248 """does a meta validation for a base.Structure.
249
250 This works by traversing the children of the structure, looking for
251 nodes with a metaModel attribute. For all these, a validation is
252 carried out. The first node failing the validation determines the
253 return value.
254
255 The function raises a MetaValidationError if aStruct is invalid.
256 """
257 _validateStructNode(aStruct)