ldpr.py 31 KB

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