ldpr.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. import logging
  2. import re
  3. from abc import ABCMeta
  4. from collections import defaultdict
  5. from threading import Thread
  6. from urllib.parse import urldefrag
  7. from uuid import uuid4
  8. import arrow
  9. from rdflib import Graph, URIRef, Literal
  10. from rdflib.compare import to_isomorphic
  11. from rdflib.namespace import RDF
  12. from lakesuperior import env, thread_env
  13. from lakesuperior.globals import (
  14. RES_CREATED, RES_DELETED, RES_UPDATED, ROOT_UID)
  15. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  16. from lakesuperior.dictionaries.srv_mgd_terms import (
  17. srv_mgd_subjects, srv_mgd_predicates, srv_mgd_types)
  18. from lakesuperior.exceptions import (
  19. InvalidResourceError, RefIntViolationError, ResourceNotExistsError,
  20. ServerManagedTermError, TombstoneError)
  21. from lakesuperior.store.ldp_rs.rsrc_centric_layout import VERS_CONT_LABEL
  22. from lakesuperior.toolbox import Toolbox
  23. rdfly = env.app_globals.rdfly
  24. logger = logging.getLogger(__name__)
  25. class Ldpr(metaclass=ABCMeta):
  26. """
  27. LDPR (LDP Resource).
  28. This class and related subclasses contain the implementation pieces of
  29. the `LDP Resource <https://www.w3.org/TR/ldp/#ldpr-resource>`__
  30. specifications, according to their `inheritance graph
  31. <https://www.w3.org/TR/ldp/#fig-ldpc-types>`__.
  32. **Note**: Even though LdpNr (which is a subclass of Ldpr) handles binary
  33. files, it still has an RDF representation in the triplestore. Hence, some
  34. of the RDF-related methods are defined in this class rather than in
  35. :class:`~lakesuperior.model.ldp_rs.LdpRs`.
  36. **Note:** Only internal facing (``info:fcres``-prefixed) URIs are handled
  37. in this class. Public-facing URI conversion is handled in the
  38. :mod:`~lakesuperior.endpoints.ldp` module.
  39. """
  40. EMBED_CHILD_RES_URI = nsc['fcrepo'].EmbedResources
  41. FCREPO_PTREE_TYPE = nsc['fcrepo'].Pairtree
  42. INS_CNT_REL_URI = nsc['ldp'].insertedContentRelation
  43. MBR_RSRC_URI = nsc['ldp'].membershipResource
  44. MBR_REL_URI = nsc['ldp'].hasMemberRelation
  45. RETURN_CHILD_RES_URI = nsc['fcrepo'].Children
  46. RETURN_INBOUND_REF_URI = nsc['fcrepo'].InboundReferences
  47. RETURN_SRV_MGD_RES_URI = nsc['fcrepo'].ServerManaged
  48. # Workflow type. Inbound means that the resource is being written to the
  49. # store, outbounnd is being retrieved for output.
  50. WRKF_INBOUND = '_workflow:inbound_'
  51. WRKF_OUTBOUND = '_workflow:outbound_'
  52. DEFAULT_USER = Literal('BypassAdmin')
  53. """
  54. Default user to be used for the `createdBy` and `lastUpdatedBy` if a user
  55. is not provided.
  56. """
  57. base_types = {
  58. nsc['fcrepo'].Resource,
  59. nsc['ldp'].Resource,
  60. nsc['ldp'].RDFSource,
  61. }
  62. """RDF Types that populate a new resource."""
  63. protected_pred = (
  64. nsc['fcrepo'].created,
  65. nsc['fcrepo'].createdBy,
  66. nsc['ldp'].contains,
  67. )
  68. """Predicates that do not get removed when a resource is replaced."""
  69. smt_allow_on_create = {
  70. nsc['ldp'].DirectContainer,
  71. nsc['ldp'].IndirectContainer,
  72. }
  73. """
  74. Server-managed RDF types ignored in the RDF payload if the resource is
  75. being created. N.B. These still raise an error if the resource exists.
  76. """
  77. delete_preds_on_replace = {
  78. nsc['ebucore'].hasMimeType,
  79. nsc['fcrepo'].lastModified,
  80. nsc['fcrepo'].lastModifiedBy,
  81. nsc['premis'].hasSize,
  82. nsc['premis'].hasMessageDigest,
  83. }
  84. """Predicates to remove when a resource is replaced."""
  85. _ignore_version_preds = {
  86. nsc['fcrepo'].hasParent,
  87. nsc['fcrepo'].hasVersions,
  88. nsc['fcrepo'].hasVersion,
  89. nsc['premis'].hasMessageDigest,
  90. nsc['ldp'].contains,
  91. }
  92. """Predicates that don't get versioned."""
  93. _ignore_version_types = {
  94. nsc['fcrepo'].Binary,
  95. nsc['fcrepo'].Container,
  96. nsc['fcrepo'].Pairtree,
  97. nsc['fcrepo'].Resource,
  98. nsc['fcrepo'].Version,
  99. nsc['ldp'].BasicContainer,
  100. nsc['ldp'].Container,
  101. nsc['ldp'].DirectContainer,
  102. nsc['ldp'].Resource,
  103. nsc['ldp'].RDFSource,
  104. nsc['ldp'].NonRDFSource,
  105. }
  106. """RDF types that don't get versioned."""
  107. ## MAGIC METHODS ##
  108. def __init__(self, uid, repr_opts={}, provided_imr=None, **kwargs):
  109. """
  110. Instantiate an in-memory LDP resource.
  111. :param str uid: uid of the resource. If None (must be explicitly
  112. set) it refers to the root node. It can also be the full URI or URN,
  113. in which case it will be converted.
  114. :param dict repr_opts: Options used to retrieve the IMR. See
  115. `parse_rfc7240` for format details.
  116. :param str provd_rdf: RDF data provided by the client in
  117. operations such as `PUT` or `POST`, serialized as a string. This sets
  118. the `provided_imr` property.
  119. """
  120. self.uid = (
  121. rdfly.uri_to_uid(uid) if isinstance(uid, URIRef) else uid)
  122. self.uri = nsc['fcres'][uid]
  123. # @FIXME Not ideal, should separate app-context dependent functions in
  124. # a different toolbox.
  125. self.tbox = Toolbox()
  126. self.provided_imr = provided_imr
  127. # Disable all internal checks e.g. for raw I/O.
  128. @property
  129. def rsrc(self):
  130. """
  131. The RDFLib resource representing this LDPR. This is a live
  132. representation of the stored data if present.
  133. :rtype: rdflib.Resource
  134. """
  135. if not hasattr(self, '_rsrc'):
  136. self._rsrc = rdfly.ds.resource(self.uri)
  137. return self._rsrc
  138. @property
  139. def imr(self):
  140. """
  141. In-Memory Resource.
  142. This is a copy of the resource extracted from the graph store. It is a
  143. graph resource whose identifier is the URI of the resource.
  144. >>> rsrc = rsrc_api.get('/')
  145. >>> rsrc.imr.identifier
  146. rdflib.term.URIRef('info:fcres/')
  147. >>> rsrc.imr.value(rsrc.imr.identifier, nsc['fcrepo'].lastModified)
  148. rdflib.term.Literal(
  149. '2018-04-03T05:20:33.774746+00:00',
  150. datatype=rdflib.term.URIRef(
  151. 'http://www.w3.org/2001/XMLSchema#dateTime'))
  152. The IMR can be read and manipulated, as well as used to
  153. update the stored resource.
  154. :rtype: rdflib.Graph
  155. :raise lakesuperior.exceptions.ResourceNotExistsError: If the resource
  156. is not stored (yet).
  157. """
  158. if not hasattr(self, '_imr'):
  159. if hasattr(self, '_imr_options'):
  160. logger.debug(
  161. 'Getting RDF representation for resource {}'
  162. .format(self.uid))
  163. #logger.debug('IMR options:{}'.format(self._imr_options))
  164. imr_options = self._imr_options
  165. else:
  166. imr_options = {}
  167. options = dict(imr_options, strict=True)
  168. self._imr = rdfly.get_imr(self.uid, **options)
  169. return self._imr
  170. @imr.setter
  171. def imr(self, v):
  172. """
  173. Replace in-memory buffered resource.
  174. :param v: New set of triples to populate the IMR with.
  175. :type v: set or rdflib.Graph
  176. """
  177. self._imr = Graph(identifier=self.uri)
  178. self._imr += v
  179. @imr.deleter
  180. def imr(self):
  181. """
  182. Delete in-memory buffered resource.
  183. """
  184. delattr(self, '_imr')
  185. @property
  186. def metadata(self):
  187. """
  188. Get resource metadata.
  189. """
  190. if not hasattr(self, '_metadata'):
  191. if hasattr(self, '_imr'):
  192. logger.info('Metadata is IMR.')
  193. self._metadata = self._imr
  194. else:
  195. logger.info(
  196. 'Getting metadata for resource {}'.format(self.uid))
  197. self._metadata = rdfly.get_metadata(self.uid)
  198. return self._metadata
  199. @metadata.setter
  200. def metadata(self, rsrc):
  201. """
  202. Set resource metadata.
  203. """
  204. if not isinstance(rsrc, Resource):
  205. raise TypeError('Provided metadata is not a Resource object.')
  206. self._metadata = rsrc
  207. @property
  208. def out_graph(self):
  209. """
  210. Retun a graph of the resource's IMR formatted for output.
  211. """
  212. out_gr = Graph(identifier=self.uri)
  213. for t in self.imr:
  214. if (
  215. # Exclude digest hash and version information.
  216. t[1] not in {
  217. #nsc['premis'].hasMessageDigest,
  218. nsc['fcrepo'].hasVersion,
  219. }
  220. ) and (
  221. # Only include server managed triples if requested.
  222. self._imr_options.get('incl_srv_mgd', True) or
  223. not self._is_trp_managed(t)
  224. ):
  225. out_gr.add(t)
  226. return out_gr
  227. @property
  228. def canonical_graph(self):
  229. """
  230. "Canonical" representation of a resource.
  231. TODO: There is no agreement yet on what a "canonical" representation
  232. of an LDP resource should be. This is a PoC method that assumes such
  233. representation to include all triples that would be retrieved with a
  234. GET request to the resource, including the ones with a different
  235. subject than the resource URI.
  236. :rtype: rdflib.compare.IsomorphicGraph
  237. """
  238. # First verify that the instance IMR options correspond to the
  239. # "canonical" representation.
  240. if (
  241. self.imr_options.get('incl_srv_mgd')
  242. and not self.imr_options.get('incl_inbound')
  243. and imr_options.get('incl_children')):
  244. gr = self.imr
  245. else:
  246. gr = rdfly.get_imr(
  247. self.uid, incl_inbound=False, incl_children=True)
  248. return to_isomorphic(gr)
  249. @property
  250. def digest(self):
  251. """
  252. Cryptographic digest of a resource.
  253. :rtype: str
  254. """
  255. return self.canonical_graph.graph_digest()
  256. @property
  257. def version_info(self):
  258. """
  259. Return version metadata (`fcr:versions`).
  260. """
  261. if not hasattr(self, '_version_info'):
  262. try:
  263. self._version_info = rdfly.get_version_info(self.uid)
  264. except ResourceNotExistsError as e:
  265. self._version_info = Graph(identifier=self.uri)
  266. return self._version_info
  267. @property
  268. def version_uids(self):
  269. """
  270. Return a generator of version UIDs (relative to their parent resource).
  271. """
  272. gen = self.version_info[
  273. self.uri:
  274. nsc['fcrepo'].hasVersion / nsc['fcrepo'].hasVersionLabel:]
  275. return {str(uid) for uid in gen}
  276. @property
  277. def is_stored(self):
  278. if not hasattr(self, '_is_stored'):
  279. if hasattr(self, '_imr'):
  280. self._is_stored = len(self.imr) > 0
  281. else:
  282. self._is_stored = rdfly.ask_rsrc_exists(self.uid)
  283. return self._is_stored
  284. @property
  285. def types(self):
  286. """All RDF types.
  287. :rtype: set(rdflib.term.URIRef)
  288. """
  289. if not hasattr(self, '_types'):
  290. if len(self.metadata):
  291. metadata = self.metadata
  292. elif getattr(self, 'provided_imr', None) and \
  293. len(self.provided_imr):
  294. metadata = self.provided_imr
  295. else:
  296. return set()
  297. self._types = set(metadata[self.uri: RDF.type])
  298. return self._types
  299. @property
  300. def ldp_types(self):
  301. """The LDP types.
  302. :rtype: set(rdflib.term.URIRef)
  303. """
  304. if not hasattr(self, '_ldp_types'):
  305. self._ldp_types = {t for t in self.types if nsc['ldp'] in t}
  306. return self._ldp_types
  307. ## LDP METHODS ##
  308. def head(self):
  309. """
  310. Return values for the headers.
  311. """
  312. out_headers = defaultdict(list)
  313. digest = self.metadata.value(self.uri, nsc['premis'].hasMessageDigest)
  314. if digest:
  315. etag = digest.identifier.split(':')[-1]
  316. out_headers['ETag'] = 'W/"{}"'.format(etag),
  317. last_updated_term = self.metadata.value(
  318. self.uri, nsc['fcrepo'].lastModified)
  319. if last_updated_term:
  320. out_headers['Last-Modified'] = arrow.get(last_updated_term)\
  321. .format('ddd, D MMM YYYY HH:mm:ss Z')
  322. for t in self.ldp_types:
  323. out_headers['Link'].append(
  324. '{};rel="type"'.format(t.n3()))
  325. return out_headers
  326. def get_version(self, ver_uid, **kwargs):
  327. """
  328. Get a version by label.
  329. """
  330. return rdfly.get_imr(self.uid, ver_uid, **kwargs)
  331. def create_or_replace(self, create_only=False):
  332. """
  333. Create or update a resource. PUT and POST methods, which are almost
  334. identical, are wrappers for this method.
  335. :param boolean create_only: Whether this is a create-only operation.
  336. """
  337. create = create_only or not self.is_stored
  338. ev_type = RES_CREATED if create else RES_UPDATED
  339. self._add_srv_mgd_triples(create)
  340. ref_int = rdfly.config['referential_integrity']
  341. if ref_int:
  342. self._check_ref_int(ref_int)
  343. # Delete existing triples if replacing.
  344. if not create:
  345. rdfly.truncate_rsrc(self.uid)
  346. remove_trp = {
  347. (self.uri, pred, None) for pred in self.delete_preds_on_replace}
  348. add_trp = (
  349. set(self.provided_imr) |
  350. self._containment_rel(create))
  351. self.modify(ev_type, remove_trp, add_trp)
  352. new_gr = Graph(identifier=self.uri)
  353. for trp in add_trp:
  354. new_gr.add(trp)
  355. self.imr = new_gr
  356. return ev_type
  357. def bury(self, inbound, tstone_pointer=None):
  358. """
  359. Delete a single resource and create a tombstone.
  360. :param bool inbound: Whether inbound relationships are
  361. removed. If ``False``, resources will keep referring
  362. to the deleted resource; their link will point to a tombstone
  363. (which will raise a ``TombstoneError`` in the Python API or a
  364. ``410 Gone`` in the LDP API).
  365. :param rdflib.URIRef tstone_pointer: If set to a URI, this creates a
  366. pointer to the tombstone of the resource that used to contain the
  367. deleted resource. Otherwise the deleted resource becomes a
  368. tombstone.
  369. """
  370. logger.info('Burying resource {}'.format(self.uid))
  371. # ldp:Resource is also used in rdfly.ask_rsrc_exists.
  372. remove_trp = {
  373. (nsc['fcrepo'].uid, nsc['rdf'].type, nsc['ldp'].Resource)
  374. }
  375. if tstone_pointer:
  376. add_trp = {
  377. (self.uri, nsc['fcsystem'].tombstone, tstone_pointer)}
  378. else:
  379. add_trp = {
  380. (self.uri, RDF.type, nsc['fcsystem'].Tombstone),
  381. (self.uri, nsc['fcsystem'].buried, thread_env.timestamp_term),
  382. }
  383. # Bury descendants.
  384. from lakesuperior.model.ldp_factory import LdpFactory
  385. for desc_uri in rdfly.get_descendants(self.uid):
  386. try:
  387. desc_rsrc = LdpFactory.from_stored(
  388. env.app_globals.rdfly.uri_to_uid(desc_uri),
  389. repr_opts={'incl_children' : False})
  390. except (TombstoneError, ResourceNotExistsError):
  391. continue
  392. desc_rsrc.bury(inbound, tstone_pointer=self.uri)
  393. # Cut inbound relationships
  394. if inbound:
  395. for ib_rsrc_uri in self.imr.subjects(None, self.uri):
  396. remove_trp = {(ib_rsrc_uri, None, self.uri)}
  397. ib_rsrc = Ldpr(ib_rsrc_uri)
  398. # To preserve inbound links in history, create a snapshot
  399. ib_rsrc.create_version()
  400. ib_rsrc.modify(RES_UPDATED, remove_trp)
  401. self.modify(RES_DELETED, remove_trp, add_trp)
  402. return RES_DELETED
  403. def forget(self, inbound=True):
  404. """
  405. Remove all traces of a resource and versions.
  406. """
  407. logger.info('Purging resource {}'.format(self.uid))
  408. refint = rdfly.config['referential_integrity']
  409. inbound = True if refint else inbound
  410. for desc_uri in rdfly.get_descendants(self.uid):
  411. rdfly.forget_rsrc(rdfly.uri_to_uid(desc_uri), inbound)
  412. rdfly.forget_rsrc(self.uid, inbound)
  413. return RES_DELETED
  414. def resurrect(self):
  415. """
  416. Resurrect a resource from a tombstone.
  417. """
  418. remove_trp = {
  419. (self.uri, nsc['rdf'].type, nsc['fcsystem'].Tombstone),
  420. (self.uri, nsc['fcsystem'].tombstone, None),
  421. (self.uri, nsc['fcsystem'].buried, None),
  422. }
  423. add_trp = {
  424. (self.uri, nsc['rdf'].type, nsc['ldp'].Resource),
  425. }
  426. self.modify(RES_CREATED, remove_trp, add_trp)
  427. # Resurrect descendants.
  428. from lakesuperior.model.ldp_factory import LdpFactory
  429. descendants = env.app_globals.rdfly.get_descendants(self.uid)
  430. for desc_uri in descendants:
  431. LdpFactory.from_stored(
  432. rdfly.uri_to_uid(desc_uri), strict=False).resurrect()
  433. return self.uri
  434. def create_version(self, ver_uid=None):
  435. """
  436. Create a new version of the resource.
  437. **Note:** This creates an event only for the resource being updated
  438. (due to the added `hasVersion` triple and possibly to the
  439. ``hasVersions`` one) but not for the version being created.
  440. :param str ver_uid: Version UID. If already existing, a new version UID
  441. is minted.
  442. """
  443. if not ver_uid or ver_uid in self.version_uids:
  444. ver_uid = str(uuid4())
  445. # Create version resource from copying the current state.
  446. logger.info(
  447. 'Creating version snapshot {} for resource {}.'.format(
  448. ver_uid, self.uid))
  449. ver_add_gr = set()
  450. vers_uid = '{}/{}'.format(self.uid, VERS_CONT_LABEL)
  451. ver_uid = '{}/{}'.format(vers_uid, ver_uid)
  452. ver_uri = nsc['fcres'][ver_uid]
  453. ver_add_gr.add((ver_uri, RDF.type, nsc['fcrepo'].Version))
  454. for t in self.imr:
  455. if (
  456. t[1] == RDF.type and t[2] in self._ignore_version_types
  457. ) or t[1] in self._ignore_version_preds:
  458. pass
  459. else:
  460. ver_add_gr.add((
  461. self.tbox.replace_term_domain(t[0], self.uri, ver_uri),
  462. t[1], t[2]))
  463. rdfly.modify_rsrc(ver_uid, add_trp=ver_add_gr)
  464. # Update resource admin data.
  465. rsrc_add_gr = {
  466. (self.uri, nsc['fcrepo'].hasVersion, ver_uri),
  467. (self.uri, nsc['fcrepo'].hasVersions, nsc['fcres'][vers_uid]),
  468. }
  469. self.modify(RES_UPDATED, add_trp=rsrc_add_gr)
  470. return ver_uid
  471. def revert_to_version(self, ver_uid, backup=True):
  472. """
  473. Revert to a previous version.
  474. :param str ver_uid: Version UID.
  475. :param boolean backup: Whether to create a backup snapshot. Default is
  476. True.
  477. """
  478. # Create a backup snapshot.
  479. if backup:
  480. self.create_version()
  481. ver_gr = rdfly.get_imr(
  482. self.uid, ver_uid=ver_uid, incl_children=False)
  483. self.provided_imr = Graph(identifier=self.uri)
  484. for t in ver_gr:
  485. if not self._is_trp_managed(t):
  486. self.provided_imr.add((self.uri, t[1], t[2]))
  487. # @TODO Check individual objects: if they are repo-managed URIs
  488. # and not existing or tombstones, they are not added.
  489. return self.create_or_replace(create_only=False)
  490. def check_mgd_terms(self, trp):
  491. """
  492. Check whether server-managed terms are in a RDF payload.
  493. :param rdflib.Graph trp: The graph to validate.
  494. """
  495. subjects = {t[0] for t in trp}
  496. offending_subjects = subjects & srv_mgd_subjects
  497. if offending_subjects:
  498. if self.handling == 'strict':
  499. raise ServerManagedTermError(offending_subjects, 's')
  500. else:
  501. for s in offending_subjects:
  502. logger.info('Removing offending subj: {}'.format(s))
  503. for t in trp:
  504. if t[0] == s:
  505. trp.remove(t)
  506. predicates = {t[1] for t in trp}
  507. offending_predicates = predicates & srv_mgd_predicates
  508. # Allow some predicates if the resource is being created.
  509. if offending_predicates:
  510. if self.handling == 'strict':
  511. raise ServerManagedTermError(offending_predicates, 'p')
  512. else:
  513. for p in offending_predicates:
  514. logger.info('Removing offending pred: {}'.format(p))
  515. for t in trp:
  516. if t[1] == p:
  517. trp.remove(t)
  518. types = {t[2] for t in trp if t[1] == RDF.type}
  519. offending_types = types & srv_mgd_types
  520. if not self.is_stored:
  521. offending_types -= self.smt_allow_on_create
  522. if offending_types:
  523. if self.handling == 'strict':
  524. raise ServerManagedTermError(offending_types, 't')
  525. else:
  526. for to in offending_types:
  527. logger.info('Removing offending type: {}'.format(to))
  528. for t in trp:
  529. if t[1] == RDF.type and t[2] == to:
  530. trp.remove(t)
  531. #logger.debug('Sanitized graph: {}'.format(trp.serialize(
  532. # format='turtle').decode('utf-8')))
  533. return trp
  534. def sparql_delta(self, qry_str):
  535. """
  536. Calculate the delta obtained by a SPARQL Update operation.
  537. This is a critical component of the SPARQL update prcess and does a
  538. couple of things:
  539. 1. It ensures that no resources outside of the subject of the request
  540. are modified (e.g. by variable subjects)
  541. 2. It verifies that none of the terms being modified is server managed.
  542. This method extracts an in-memory copy of the resource and performs the
  543. query on that once it has checked if any of the server managed terms is
  544. in the delta. If it is, it raises an exception.
  545. NOTE: This only checks if a server-managed term is effectively being
  546. modified. If a server-managed term is present in the query but does not
  547. cause any change in the updated resource, no error is raised.
  548. :rtype: tuple(rdflib.Graph)
  549. :return: Remove and add graphs. These can be used
  550. with ``BaseStoreLayout.update_resource`` and/or recorded as separate
  551. events in a provenance tracking system.
  552. """
  553. logger.debug('Provided SPARQL query: {}'.format(qry_str))
  554. # Workaround for RDFLib bug. See
  555. # https://github.com/RDFLib/rdflib/issues/824
  556. qry_str = (
  557. re.sub('<#([^>]+)>', '<{}#\\1>'.format(self.uri), qry_str)
  558. .replace('<>', '<{}>'.format(self.uri)))
  559. pre_gr = Graph(identifier=self.uri)
  560. pre_gr += self.imr
  561. post_gr = Graph(identifier=self.uri)
  562. post_gr += self.imr
  563. post_gr.update(qry_str)
  564. remove_gr, add_gr = self._dedup_deltas(pre_gr, post_gr)
  565. #logger.debug('Removing: {}'.format(
  566. # remove_gr.serialize(format='turtle').decode('utf8')))
  567. #logger.debug('Adding: {}'.format(
  568. # add_gr.serialize(format='turtle').decode('utf8')))
  569. remove_trp = self.check_mgd_terms(set(remove_gr))
  570. add_trp = self.check_mgd_terms(set(add_gr))
  571. return remove_trp, add_trp
  572. ## PROTECTED METHODS ##
  573. def _is_trp_managed(self, t):
  574. """
  575. Whether a triple is server-managed.
  576. :param tuple t: Triple as a 3-tuple of terms.
  577. :rtype: boolean
  578. """
  579. return t[1] in srv_mgd_predicates or (
  580. t[1] == RDF.type and t[2] in srv_mgd_types)
  581. def modify(
  582. self, ev_type, remove_trp=set(), add_trp=set()):
  583. """
  584. Low-level method to modify a graph for a single resource.
  585. This is a crucial point for messaging. Any write operation on the RDF
  586. store that needs to be notified should be performed by invoking this
  587. method.
  588. :param ev_type: The type of event (create, update,
  589. delete) or None. In the latter case, no notification is sent.
  590. :type ev_type: str or None
  591. :param set remove_trp: Triples to be removed.
  592. # Add metadata.
  593. :param set add_trp: Triples to be added.
  594. """
  595. rdfly.modify_rsrc(self.uid, remove_trp, add_trp)
  596. # Calculate checksum (asynchronously).
  597. Thread(target=self._update_checksum).run()
  598. # Clear IMR buffer.
  599. if hasattr(self, '_imr'):
  600. delattr(self, '_imr')
  601. try:
  602. self.imr
  603. except (ResourceNotExistsError, TombstoneError):
  604. pass
  605. if (
  606. ev_type is not None and
  607. env.app_globals.config['application'].get('messaging')):
  608. logger.debug('Enqueuing message for {}'.format(self.uid))
  609. self._enqueue_msg(ev_type, remove_trp, add_trp)
  610. def _update_checksum(self):
  611. """
  612. Save the resource checksum in a dedicated metadata store.
  613. """
  614. pass
  615. def _enqueue_msg(self, ev_type, remove_trp=None, add_trp=None):
  616. """
  617. Compose a message about a resource change.
  618. The message is enqueued for asynchronous processing.
  619. :param str ev_type: The event type. See global constants.
  620. :param set remove_trp: Triples removed. Only used if the
  621. """
  622. try:
  623. rsrc_type = tuple(str(t) for t in self.types)
  624. actor = self.metadata.value(self.uri, nsc['fcrepo'].createdBy)
  625. except (ResourceNotExistsError, TombstoneError):
  626. rsrc_type = ()
  627. actor = None
  628. for t in add_trp:
  629. if t[1] == RDF.type:
  630. rsrc_type.add(t[2])
  631. elif actor is None and t[1] == nsc['fcrepo'].createdBy:
  632. actor = t[2]
  633. env.app_globals.changelog.append((set(remove_trp), set(add_trp), {
  634. 'ev_type': ev_type,
  635. 'timestamp': thread_env.timestamp.format(),
  636. 'rsrc_type': rsrc_type,
  637. 'actor': actor,
  638. }))
  639. def _check_ref_int(self, config):
  640. """
  641. Check referential integrity of a resource.
  642. :param str config: If set to ``strict``, a
  643. :class:`lakesuperior.exceptions.RefIntViolationError` is raised.
  644. Otherwise, the violation is simply logged.
  645. """
  646. for o in self.provided_imr.objects():
  647. if(
  648. isinstance(o, URIRef) and
  649. str(o).startswith(nsc['fcres']) and
  650. urldefrag(o).url.rstrip('/') != str(self.uri)):
  651. obj_uid = rdfly.uri_to_uid(o)
  652. if not rdfly.ask_rsrc_exists(obj_uid):
  653. if config == 'strict':
  654. raise RefIntViolationError(obj_uid)
  655. else:
  656. logger.info(
  657. 'Removing link to non-existent repo resource: {}'
  658. .format(obj_uid))
  659. self.provided_imr.remove((None, None, o))
  660. def _add_srv_mgd_triples(self, create=False):
  661. """
  662. Add server-managed triples to a provided IMR.
  663. :param create: Whether the resource is being created.
  664. """
  665. # Base LDP types.
  666. for t in self.base_types:
  667. self.provided_imr.add((self.uri, RDF.type, t))
  668. # Create and modify timestamp.
  669. if create:
  670. self.provided_imr.set((
  671. self.uri, nsc['fcrepo'].created, thread_env.timestamp_term))
  672. self.provided_imr.set((
  673. self.uri, nsc['fcrepo'].createdBy, self.DEFAULT_USER))
  674. else:
  675. self.provided_imr.set((
  676. self.uri, nsc['fcrepo'].created, self.metadata.value(
  677. self.uri, nsc['fcrepo'].created)))
  678. self.provided_imr.set((
  679. self.uri, nsc['fcrepo'].createdBy, self.metadata.value(
  680. self.uri, nsc['fcrepo'].createdBy)))
  681. self.provided_imr.set((
  682. self.uri, nsc['fcrepo'].lastModified, thread_env.timestamp_term))
  683. self.provided_imr.set((
  684. self.uri, nsc['fcrepo'].lastModifiedBy, self.DEFAULT_USER))
  685. def _containment_rel(self, create, ignore_type=True):
  686. """Find the closest parent in the path indicated by the uid and
  687. establish a containment triple.
  688. Check the path-wise parent of the new resource. If it exists, add the
  689. containment relationship with this UID. Otherwise, create a container
  690. resource as the parent.
  691. This function may recurse up the path tree until an existing container
  692. is found.
  693. E.g. if only fcres:/a exists:
  694. - If ``fcres:/a/b/c/d`` is being created, a becomes container of
  695. ``fcres:/a/b/c/d``. Also, containers are created for fcres:a/b and
  696. ``fcres:/a/b/c``.
  697. - If ``fcres:/e`` is being created, the root node becomes container of
  698. ``fcres:/e``.
  699. :param bool create: Whether the resource is being created. If false,
  700. the parent container is not updated.
  701. "param bool ignore_type: If False (the default), an exception is raised
  702. if trying to create a resource under a non-container. This can be
  703. overridden in special cases (e.g. when migrating a repository in which
  704. a LDP-NR has "children" under ``fcr:versions``) by setting this to
  705. True.
  706. """
  707. from lakesuperior.model.ldp_factory import LdpFactory
  708. if '/' in self.uid.lstrip('/'):
  709. # Traverse up the hierarchy to find the parent.
  710. path_components = self.uid.lstrip('/').split('/')
  711. cnd_parent_uid = '/' + '/'.join(path_components[:-1])
  712. if rdfly.ask_rsrc_exists(cnd_parent_uid):
  713. parent_rsrc = LdpFactory.from_stored(cnd_parent_uid)
  714. if (
  715. not ignore_type
  716. and nsc['ldp'].Container not in parent_rsrc.types):
  717. raise InvalidResourceError(
  718. cnd_parent_uid, 'Parent {} is not a container.')
  719. parent_uid = cnd_parent_uid
  720. else:
  721. parent_rsrc = LdpFactory.new_container(cnd_parent_uid)
  722. # This will trigger this method again and recurse until an
  723. # existing container or the root node is reached.
  724. parent_rsrc.create_or_replace()
  725. parent_uid = parent_rsrc.uid
  726. else:
  727. parent_uid = ROOT_UID
  728. parent_rsrc = LdpFactory.from_stored(
  729. parent_uid, repr_opts={'incl_children': False}, handling='none')
  730. # Only update parent if the resource is new.
  731. if create:
  732. add_gr = Graph()
  733. add_gr.add(
  734. (nsc['fcres'][parent_uid], nsc['ldp'].contains, self.uri))
  735. parent_rsrc.modify(RES_UPDATED, add_trp=add_gr)
  736. # Direct or indirect container relationship.
  737. return self._add_ldp_dc_ic_rel(parent_rsrc)
  738. def _dedup_deltas(self, remove_gr, add_gr):
  739. """
  740. Remove duplicate triples from add and remove delta graphs, which would
  741. otherwise contain unnecessary statements that annul each other.
  742. :rtype: tuple
  743. :return: 2 "clean" sets of respectively remove statements and
  744. add statements.
  745. """
  746. return (
  747. remove_gr - add_gr,
  748. add_gr - remove_gr
  749. )
  750. def _add_ldp_dc_ic_rel(self, cont_rsrc):
  751. """
  752. Add relationship triples from a parent direct or indirect container.
  753. :param rdflib.resource.Resouce cont_rsrc: The container resource.
  754. """
  755. cont_p = set(cont_rsrc.metadata.predicates())
  756. logger.info('Checking direct or indirect containment.')
  757. logger.debug('Parent predicates: {}'.format(cont_p))
  758. add_trp = {(self.uri, nsc['fcrepo'].hasParent, cont_rsrc.uri)}
  759. if self.MBR_RSRC_URI in cont_p and self.MBR_REL_URI in cont_p:
  760. from lakesuperior.model.ldp_factory import LdpFactory
  761. s = cont_rsrc.metadata.value(cont_rsrc.uri, self.MBR_RSRC_URI)
  762. p = cont_rsrc.metadata.value(cont_rsrc.uri, self.MBR_REL_URI)
  763. if nsc['ldp'].DirectContainer in cont_rsrc.ldp_types:
  764. logger.info('Parent is a direct container.')
  765. logger.debug('Creating DC triples.')
  766. o = self.uri
  767. elif nsc['ldp'].IndirectContainer in cont_rsrc.ldp_types:
  768. logger.info('Parent is an indirect container.')
  769. cont_rel_uri = cont_rsrc.metadata.value(
  770. cont_rsrc.uri, self.INS_CNT_REL_URI)
  771. o = self.provided_imr.value(self.uri, cont_rel_uri)
  772. logger.debug('Target URI: {}'.format(o))
  773. logger.debug('Creating IC triples.')
  774. target_rsrc = LdpFactory.from_stored(rdfly.uri_to_uid(s))
  775. target_rsrc.modify(RES_UPDATED, add_trp={(s, p, o)})
  776. return add_trp