ldpr.py 31 KB

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