Debian Codegraph @

gavo/web/tap_uploads.py

raw
1 """
2 TAP 1.2 prototype persistent TAP uploads.
3
4 These are implemented as renderers that might work on stuff other than
5 TAP, but I'm not sure there is a case to be made for persistent *table*
6 uploads on anything else. And anyway: these tables have extra features
7 to be TAP accessible, and they are managed through the
8 TAP_SCHEMA.persistent_uploads table.
9 """
10
11 #c Copyright 2008-2025, the GAVO project <[email protected]>
12 #c
13 #c This program is free software, covered by the GNU GPL. See the
14 #c COPYING file in the source distribution.
15
16
17 import datetime
18 import functools
19 import re
20
21 from twisted.internet import threads
22 from twisted.web import resource
23 from twisted.web import server
24
25 from gavo import base
26 from gavo import formats
27 from gavo import rsc
28 from gavo import rscdef
29 from gavo import svcs
30 from gavo import utils
31 from gavo.base import valuemappers
32 from gavo.formats import votableread
33 from gavo.protocols import dali
34 from gavo.protocols import uws
35 from gavo.protocols import useruws
36 from gavo.registry import tableset
37 from gavo.web import vodal
38 from gavo.web.vosi import VTM
39
40
41 USER_TABLE_NAME_PATTERN = re.compile(r"[a-z][a-z0-9_]*$")
42
43 MS = base.makeStruct
44
45
46 @functools.cache
47 def getIndexerUWS():
48 return useruws.makeUWSForService(
49 base.resolveCrossId("//tap_user#create-index"))
50
51
52 def createIndex(user, tableName, indexName):
53 """actually creates an index for an uploaded table.
54
55 This is called from within //tap_user#create-index.
56 """
57 td, physicalName = getUploadedTableDef(user, tableName)
58 td.id = physicalName.split(".")[-1]
59 td.onDisk = True
60 for index in td.indices:
61 if index.name==indexName:
62 break
63 else:
64 raise base.NotFoundError(tableName, "Uploaded table" f"uploads for {user}")
65
66 with base.getWritableAdminConn() as conn:
67 table = rsc.TableForDef(td, connection=conn)
68 index.create(table, notify=False)
69
70
71 def _getBaseUCD(ucd):
72 """returns a basis UCD for spatial UCDs.
73
74 This is only useful for _customizeIndex.
75 """
76 return ".".join(ucd.split(";")[0].split(".")[:-1])
77
78
79 def _customizeIndex(columns):
80 """returns extra DBIndex attributes to create indexes for specific sorts
81 of columns.
82 """
83 if len(columns)==1 and columns[0].type=="spoint":
84 return {"cluster": True, "kind": "spoint", "method": "GIST"}
85
86 elif len(columns)==2:
87 latCol, lonCol = None, None
88 for col in columns:
89 if col.ucd.split(";")[0] in {
90 "pos.eq.ra", "pos.galactic.lon", "pos.earth.lon",
91 "pos.ecliptic.lon"}:
92 if col.unit=="deg":
93 lonCol = col
94 if col.ucd.split(";")[0] in {
95 "pos.eq.dec", "pos.galactic.lat", "pos.earth.lat",
96 "pos.ecliptic.lat"}:
97 if col.unit=="deg":
98 latCol = col
99
100 # The _getBaseUCD condition below is a bit questionable: Shouldn't
101 # we error out on these? Mixing different coordinate flavours
102 # probably is never sensible, but silently refusing to do a
103 # spatial index on them doesn't *quite* feel right either.
104 if (latCol is not None and lonCol is not None
105 and _getBaseUCD(latCol.ucd)==_getBaseUCD(lonCol.ucd)):
106 indexType = base.getConfig("db", "splitSpatialIndex")
107 if indexType=="q3c":
108 return {"cluster": True,
109 "content_": f"q3c_ang2ipix({lonCol.name}),{latCol.name})"}
110 elif indexType=="pgsphere":
111 return {"cluster": True, "method": "GIST", "kind": "spoint",
112 "content_": f"spoint(radians({lonCol.name}),radians({latCol.name}))"}
113 else:
114 raise Exception(f"Unknown spatial index method {indexType}")
115
116 return {}
117
118
119 def dropUserUploadedTable(conn, user, tableName):
120 """drops a user-uploaded table.
121
122 This will drop both the entry in the management table and the table
123 itself. It is not an error to request dropping a non-existing table;
124 that's a no-op, though.
125 """
126 constraints = {"user": user, "tablename": tableName}
127 res = list(conn.query("select physical_name from tap_user.tables"
128 " WHERE user_name=%(user)s and table_name=%(tablename)s",
129 constraints))
130 if res:
131 physicalName = res[0][0]
132 conn.execute(f"DROP TABLE IF EXISTS {physicalName}")
133
134 conn.execute("DELETE FROM tap_user.tables"
135 " WHERE user_name=%(user)s and table_name=%(tablename)s",
136 constraints)
137
138
139 def getUploadedTableDef(user, tableName):
140 """returns an rsc.TableDef for an uploaded table for user together with
141 its physical name.
142
143 This will raise an UnknownURI if no such table exists.
144 """
145 with base.getTableConn() as conn:
146 try:
147 cursor = conn.query(
148 "SELECT metadata, physical_name"
149 " FROM tap_user.tables"
150 " WHERE user_name=%(user)s and table_name=%(tablename)s",
151 {"user": user, "tablename": tableName})
152 rawTD, physicalName = next(cursor)
153 except StopIteration:
154 raise svcs.UnknownURI(f"No such uploaded table for user {user}")
155
156 # Defensive programming: Make sure there's only one match
157 try:
158 next(cursor)
159 except StopIteration:
160 pass
161 else:
162 # this can't happen
163 raise Exception("Two matches for uploaded table")
164
165 td = base.parseFromString(rscdef.TableDef, rawTD)
166 td.parent = base.caches.getRD("//tap_user")
167 return td, physicalName
168
169
170 def uploadUserTable(conn, tableName, srcFile, user):
171 """actually performs a table ingestion.
172
173 It arranges for the data in the VOTable readable from srcFile
174 will be tap_user.tableName for user, while it is actually
175 stored in tap_user.<something else>. That something else,
176 the physcial_name, is returned by this function.
177
178 The function also performs the basic bookkeeping, including storing a
179 VODataService tableset in tap_user.tables.
180 """
181 if valuemappers.needsQuoting(tableName):
182 raise base.ReportableError(f"'{tableName}' cannot be used as"
183 " an upload table name (which must be regular ADQL identifiers,"
184 " in particular not ADQL reserved words).")
185
186 # this is where the physical name is defined. Everyone else
187 # must get it from the physcial_name column, as this rule
188 # will probably change.
189 physicalName = f"tap_user._{user}_{tableName}"
190 if not re.match(r"tap_user\.[a-z_0-9]+$", physicalName):
191 raise base.ReportableError("Bad generated table name. Giving up.")
192 if base.UnmanagedQuerier(conn).getTableType(physicalName):
193 conn.execute(f"DROP table IF EXISTS {physicalName}")
194
195 if srcFile:
196 uploadedTable = votableread.uploadVOTable(
197 physicalName.split(".")[-1],
198 srcFile,
199 conn,
200 nameMaker=votableread.AutoQuotedNameMaker(),
201 rd=base.caches.getRD("//tap_user"),
202 temporary=False,
203 adql=True)
204 serialised = serialiseTD(uploadedTable.tableDef, tableName)
205
206 else:
207 # without a source file, this is just an allocation (for create table),
208 # and we have no idea about the table structure. Do a placeholder:
209 serialised = f'<table id="{tableName}">'
210
211 tablesTable = rsc.TableForDef(
212 base.resolveCrossId("//tap_user#tables"),
213 connection=conn)
214 tablesTable.addRow({
215 "user_name": user,
216 "table_name": tableName,
217 "physical_name": physicalName,
218 "metadata": serialised,
219 "expiry": datetime.datetime.utcnow()
220 +datetime.timedelta(days=base.getConfig("ivoa", "userTableDays"))})
221
222 return physicalName
223
224
225 class ResourceWithDALIErrors(resource.Resource):
226 """A class that tries to produce DALI errors on almost all that
227 can go wrong in the sync case.
228
229 To work this, don't override render and getChild but render_METHOD
230 and _getChildReal. Only sync errors will be handled, when you defer,
231 you need to call addErrback(self._renderError, request) yourself.
232 _renderError finishes the request itself.
233 """
234 def render(self, request):
235 try:
236 return resource.Resource.render(self, request)
237 except Exception as exc:
238 if not isinstance(exc, svcs.Error):
239 base.ui.notifyError(str(exc))
240 return dali.serveDALIError(request, exc)
241
242 def _renderError(self, flr, request):
243 base.ui.notifyFailure(flr)
244 dali.serveDALIError(request, flr.value)
245 return server.NOT_DONE_YET
246
247 def serveImmediate(self, request, mediaType, content):
248 request.setHeader("content-type", mediaType)
249 request.write(utils.bytify(content))
250 request.finish()
251 return server.NOT_DONE_YET
252
253 def _getChildReal(self, name, request):
254 raise svcs.UnknownURI("{self.__class__.__name__} has no children")
255
256 def getChild(self, name, request):
257 try:
258 return self._getChildReal(utils.debytify(name), request)
259 except Exception as exc:
260 return dali.DALIErrorResource(exc)
261
262
263 def serialiseTD(tableDef, logicalName):
264 """returns RD XML for tableDef.
265 """
266 # we need to manually give the table an id because structToXML
267 # swallows these. I suppose there should be a way to presere
268 # id-s in that function, but knowing when to drop an id and
269 # when to preserve it is not simple; note that you cannot
270 # TableForDef these TDs because their physical name is differnt
271 # from their id.
272 return base.structToXML(tableDef).replace(
273 "<table>", f'<table id="{logicalName}">')
274
275
276 class PersistentUploadResource(ResourceWithDALIErrors):
277 """a resource operating on a persistent table upload.
278
279 These are all constructed with the table name in question, which
280 is the logical name without the tap_user schema. Note that
281 depending on which user is encoded in the request handled, this
282 may refer to different physical tables.
283 """
284 def __init__(self, tableName):
285 self.tableName = tableName
286 ResourceWithDALIErrors.__init__(self)
287
288
289 def _getCurrentTD(self, request):
290 """returns a TableDef for the user uploaded table for this request.
291 """
292 user = request.getAuthUser() or "anonymous"
293 return getUploadedTableDef(user, self.tableName)[0]
294
295
296 class DestructionTimeManager(PersistentUploadResource):
297 """a resource for setting and retrieving the life time of an
298 uploaded table.
299
300 This handles the destruction child of the table resource.
301 """
302 def getGrammar(self):
303 return MS(svcs.ContextGrammar,
304 inputKeys=[MS(svcs.InputKey,
305 name="DESTRUCTION",
306 type="timestamp",
307 tablehead="Delete at",
308 description="DALI-type ISO timestamp for when this table should"
309 " be dropped automatically.",
310 multiplicity="single")])
311
312 def render_POST(self, request):
313 user = request.getAuthUser() or "anonymous"
314 parsed = self.getGrammar().parseStrargs(request.strargs)
315
316 if not parsed["DESTRUCTION"]:
317 raise svcs.BadRequestion("DESTRUCTION parameter required on POST")
318
319 destructionTime = parsed["DESTRUCTION"]
320
321 # let's have a hard limit of a year for now
322 limit = datetime.datetime.now()+datetime.timedelta(days=366)
323 newExpiry = min(destructionTime, limit)
324
325 with base.getWritableTableConn() as conn:
326 conn.execute("UPDATE tap_user.tables"
327 " SET expiry=%(expiry)s"
328 " WHERE user_name=%(user)s and table_name=%(tablename)s", {
329 "user": user,
330 "tablename": self.tableName,
331 "expiry": newExpiry})
332
333 return self.render_GET(request)
334
335 def render_GET(self, request):
336 user = request.getAuthUser() or "anonymous"
337 with base.getWritableTableConn() as conn:
338 res = conn.query("SELECT expiry FROM tap_user.tables"
339 " WHERE user_name=%(user)s and table_name=%(tablename)s", {
340 "user": user,
341 "tablename": self.tableName})
342
343 expiry = next(res)[0]
344 request.setHeader("content-type", "text/plain; charset=utf-8")
345 return utils.bytify(utils.formatISODT(expiry))
346
347
348 class IndexManager(PersistentUploadResource):
349 """The index child of a persistently uploaded table.
350
351 POST creates an index (possibly of special kinds), GET returns
352 a human-readable non-standard text representation of the indexes.
353 """
354 def getGrammar(self):
355 return MS(svcs.ContextGrammar,
356 inputKeys=[MS(svcs.InputKey,
357 name="INDEX",
358 type="text",
359 tablehead="Index column(s)",
360 description="A name of a column to index. This parameter can"
361 " be repeated to create joint indexes; a particularly common"
362 " reason to simulatneously index multiple columns is spherical"
363 " coordinates. DaCHS will use an appropriate spatial indexing"
364 " method if it detects that situation (by using UCDs).",
365 multiplicity="multiple")])
366
367 def _startIndexCreation(self, request, indexNames, user):
368 td = self._getCurrentTD(request)
369 indexColumns = []
370 for name in indexNames:
371 try:
372 indexColumns.append(td.getColumnByName(name))
373 except base.NotFoundError:
374 raise svcs.BadRequest(f"No such column: {name}")
375
376 newIndex = MS(
377 rscdef.DBIndex,
378 columns=indexNames,
379 **_customizeIndex(indexColumns))
380
381 # we want to overwrite indexes with the same names so you can
382 # update indexes rather than accumulate them
383 for indind, ind in enumerate(td.indices):
384 if ind.name==newIndex.name:
385 with base.getWritableAdminConn() as conn:
386 ind.drop(base.UnmanagedQuerier(conn))
387 td.indices[indind] = newIndex
388 break
389 else:
390 td.indices.append(newIndex)
391
392 newMetadata = serialiseTD(td, self.tableName)
393
394 with base.getWritableTableConn() as conn:
395 res = conn.execute("UPDATE tap_user.tables"
396 " SET metadata=%(metadata)s"
397 " WHERE user_name=%(user)s and table_name=%(tablename)s", {
398 "user": user,
399 "tablename": self.tableName,
400 "metadata": newMetadata})
401 if res!=1:
402 raise base.DBError(
403 f"Failed to update metadata for table {self.tableName}")
404
405 ws = getIndexerUWS()
406 uwsUser = user if user!="anonymous" else None
407 jobId = ws.getNewIdFromArgs(
408 {},
409 {"table_name": self.tableName, "index_name": newIndex.name},
410 uwsUser)
411 ws.changeToPhase(jobId, uws.QUEUED)
412
413 raise svcs.SeeOther(ws.getJob(jobId).getURL())
414
415 def render_POST(self, request):
416 user = request.getAuthUser() or "anonymous"
417 parsed = self.getGrammar().parseStrargs(request.strargs)
418 if not parsed["INDEX"]:
419 raise svcs.BadRequestion("INDEX parameter required on POST")
420 return self._startIndexCreation(request, parsed["INDEX"], user)
421
422 def render_GET(self, request):
423 td, _ = getUploadedTableDef(
424 request.getAuthUser() or "anonymous", self.tableName)
425 res = [f"Indexes on table tap_user.{self.tableName}\n"]
426 if td.indices:
427 for ind in td.indices:
428 for statement in ind.iterCode():
429 res.append(statement)
430 else:
431 res.append("(none)")
432
433 request.setHeader("content-type", "text/plain; charset=utf-8")
434 return utils.bytify("\n".join(res)+"\n")
435
436
437 class PersistentUploadManager(PersistentUploadResource):
438 """A resource corresponding to a persistently uploaded table.
439
440 It is created by a put request. A GET will yield a VODataService tablset,
441 a DELETE will remove the table. POST is undefined so far,
442 but there's management children destruction and index.
443
444 These are exclusively created by the PersistentUploadRenderer.
445 """
446 def render_PUT(self, request):
447 user = request.getAuthUser() or "anonymous"
448 # for now, we try to get away with a computed physical name:
449 # _<user>_<user-table-name>. This *could* work because we
450 # forbid leading underscores in our <user-table-name>-s. This
451 # will break (without delimited table identifiers) when our user
452 # names become complicated.
453 mediaType = request.getHeader("content-type")
454 if mediaType is None:
455 raise svcs.BadRequest("Missing payload media type")
456
457 # normalise the media type so we can more easily recognised VOTables
458 try:
459 incomingFormat = formats.getMIMEFor(formats.getKeyFor(mediaType))
460 if not "votable" in incomingFormat:
461 raise formats.CannotSerializeIn("Really, parse from non-VOTable")
462 except formats.CannotSerializeIn:
463 raise svcs.BadRequest(f"Do not know how to ingest {mediaType} tables",
464 hint="We accept VOTables with many media types; if in"
465 " doubt, use application/x-votable+xml")
466
467 # defer the rest into a thread; it's hard to make this async with
468 # what we have.
469 d = threads.deferToThread(self._perform_upload, request, user)
470 d.addErrback(self._renderError, request)
471 return server.NOT_DONE_YET
472
473 def _perform_upload(self, request, user):
474 with base.getWritableAdminConn() as conn:
475 uploadUserTable(conn, self.tableName, request.content, user)
476
477 self.serveImmediate(request, "text/plain; charset=utf-8",
478 f"Query this table as tap_user.{self.tableName}\n")
479
480 def render_GET(self, request):
481 td = self._getCurrentTD(request)
482 et = tableset.getTableForTableDef(td, set(), rootElement=VTM.table)
483
484 request.setHeader("content-type", "text/xml")
485 utils.xmlwrite(et, request,
486 prolog="<?xml-stylesheet href='/static/xsl/vosi.xsl' type='text/xsl'?>")
487 return b""
488
489 def render_DELETE(self, request):
490 user = request.getAuthUser() or "anonymous"
491 with base.getWritableAdminConn() as conn:
492 try:
493 # dropUserUploadedTable fails silently, but we want
494 # to raise an error, so let's make sure the table
495 # to drop actually exists.
496 next(conn.query(
497 "SELECT physical_name FROM tap_user.tables"
498 " WHERE user_name=%(user)s and table_name=%(tablename)s",
499 {"user": user, "tablename": self.tableName}))[0]
500 except StopIteration:
501 raise svcs.UnknownURI(f"No such uploaded table for user {user}")
502
503 dropUserUploadedTable(conn, user, self.tableName)
504
505 return self.serveImmediate(request,
506 "text/plain; charset=utf-8", f"Dropped user table {self.tableName}\n")
507
508 def getChild(self, name, request):
509 name = name.decode("ascii")
510 if name=="destruction":
511 return DestructionTimeManager(self.tableName)
512 elif name=="index":
513 return IndexManager(self.tableName)
514 else:
515 raise svcs.UnknownURI("Unsupported child resource: {name}")
516
517
518 class PersistentUploadRenderer(vodal.UnifiedDALRenderer):
519 """A renderer for creating and deleting persistent TAP-queriable tables.
520
521 This really only makes sense on the TAP service.
522 """
523 name = "user_tables"
524 standardId = "ivo://ivoa.net/std/tap#persistent-uploads-1.2"
525 resultType = "text/html"
526
527 def render(self, request):
528 user = request.getAuthUser() or "anonymous"
529 if user=="anonymous":
530 return dali.serveDALIError(
531 request,
532 svcs.ForbiddenURI("No persistent tables listing for"
533 " anonymous users."))
534
535 # this returns a VOSI tableset for the uploads made by this user
536 with base.getTableConn() as conn:
537 rawTDs = conn.query("SELECT metadata FROM tap_user.tables"
538 " WHERE user_name=%(user)s", {"user": user})
539
540 rd = base.caches.getRD("//tap_user")
541 tds = []
542 for (rawTD,) in rawTDs:
543 td = base.parseFromString(rscdef.TableDef, rawTD)
544 td.parent = rd
545 tds.append(td)
546
547 et = tableset.getTablesetForSchemaCollection(
548 [(rd, tds)], rootElement=VTM.tableset)
549 request.setHeader("content-type", "text/xml")
550 utils.xmlwrite(et, request,
551 prolog="<?xml-stylesheet href='/static/xsl/vosi.xsl' type='text/xsl'?>")
552 return b""
553
554 def getChild(self, name, request):
555 try:
556 name = name.decode("ascii", "replace")
557 if not USER_TABLE_NAME_PATTERN.match(name):
558 raise svcs.UnknownURI("You must give a valid upload table name here")
559
560 with base.getTableConn() as conn:
561 if base.UnmanagedQuerier(conn).getTableType("tap_user.tables"
562 )!="BASE TABLE":
563 raise svcs.ForbiddenURI(
564 "Persistent table uploads not enabled on this instance.")
565
566 return PersistentUploadManager(name)
567 except Exception as exc:
568 if not isinstance(exc, svcs.Error):
569 base.ui.notifyError(exc)
570 return dali.DALIErrorResource(exc)