ldpr.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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. from rdflib import Graph, URIRef, Literal
  14. from rdflib.compare import to_isomorphic
  15. from rdflib.namespace import RDF
  16. from lakesuperior import env, thread_env
  17. from lakesuperior.globals import (
  18. RES_CREATED, RES_DELETED, RES_UPDATED, ROOT_UID)
  19. from lakesuperior.dictionaries.namespaces import ns_collection as nsc
  20. from lakesuperior.dictionaries.srv_mgd_terms import (
  21. srv_mgd_subjects, srv_mgd_predicates, srv_mgd_types)
  22. from lakesuperior.exceptions import (
  23. InvalidResourceError, RefIntViolationError, ResourceNotExistsError,
  24. ServerManagedTermError, TombstoneError)
  25. from lakesuperior.model.graph.graph import SimpleGraph, Imr
  26. from lakesuperior.store.ldp_rs.rsrc_centric_layout import VERS_CONT_LABEL
  27. from lakesuperior.toolbox import Toolbox
  28. rdfly = env.app_globals.rdfly
  29. logger = logging.getLogger(__name__)
  30. class Ldpr(metaclass=ABCMeta):
  31. """
  32. LDPR (LDP Resource).
  33. This class and related subclasses contain the implementation pieces of
  34. the `LDP Resource <https://www.w3.org/TR/ldp/#ldpr-resource>`__
  35. specifications, according to their `inheritance graph
  36. <https://www.w3.org/TR/ldp/#fig-ldpc-types>`__.
  37. **Note**: Even though LdpNr (which is a subclass of Ldpr) handles binary
  38. files, it still has an RDF representation in the triplestore. Hence, some
  39. of the RDF-related methods are defined in this class rather than in
  40. :class:`~lakesuperior.model.ldp.ldp_rs.LdpRs`.
  41. **Note:** Only internal facing (``info:fcres``-prefixed) URIs are handled
  42. in this class. Public-facing URI conversion is handled in the
  43. :mod:`~lakesuperior.endpoints.ldp` module.
  44. """
  45. EMBED_CHILD_RES_URI = nsc['fcrepo'].EmbedResources
  46. FCREPO_PTREE_TYPE = nsc['fcrepo'].Pairtree
  47. INS_CNT_REL_URI = nsc['ldp'].insertedContentRelation
  48. MBR_RSRC_URI = nsc['ldp'].membershipResource
  49. MBR_REL_URI = nsc['ldp'].hasMemberRelation
  50. RETURN_CHILD_RES_URI = nsc['fcrepo'].Children
  51. RETURN_INBOUND_REF_URI = nsc['fcrepo'].InboundReferences
  52. RETURN_SRV_MGD_RES_URI = nsc['fcrepo'].ServerManaged
  53. # Workflow type. Inbound means that the resource is being written to the
  54. # store, outbounnd is being retrieved for output.
  55. WRKF_INBOUND = '_workflow:inbound_'
  56. WRKF_OUTBOUND = '_workflow:outbound_'
  57. DEFAULT_USER = Literal('BypassAdmin')
  58. """
  59. Default user to be used for the `createdBy` and `lastUpdatedBy` if a user
  60. is not provided.
  61. """
  62. base_types = {
  63. nsc['fcrepo'].Resource,
  64. nsc['ldp'].Resource,
  65. nsc['ldp'].RDFSource,
  66. }
  67. """RDF Types that populate a new resource."""
  68. protected_pred = (
  69. nsc['fcrepo'].created,
  70. nsc['fcrepo'].createdBy,
  71. nsc['ldp'].contains,
  72. )
  73. """Predicates that do not get removed when a resource is replaced."""
  74. smt_allow_on_create = {
  75. nsc['ldp'].DirectContainer,
  76. nsc['ldp'].IndirectContainer,
  77. }
  78. """
  79. Server-managed RDF types ignored in the RDF payload if the resource is
  80. being created. N.B. These still raise an error if the resource exists.
  81. """
  82. delete_preds_on_replace = {
  83. nsc['ebucore'].hasMimeType,
  84. nsc['fcrepo'].lastModified,
  85. nsc['fcrepo'].lastModifiedBy,
  86. nsc['premis'].hasSize,
  87. nsc['premis'].hasMessageDigest,
  88. }
  89. """Predicates to remove when a resource is replaced."""
  90. _ignore_version_preds = {
  91. nsc['fcrepo'].hasParent,
  92. nsc['fcrepo'].hasVersions,
  93. nsc['fcrepo'].hasVersion,
  94. nsc['premis'].hasMessageDigest,
  95. nsc['ldp'].contains,
  96. }
  97. """Predicates that don't get versioned."""
  98. _ignore_version_types = {
  99. nsc['fcrepo'].Binary,
  100. nsc['fcrepo'].Container,
  101. nsc['fcrepo'].Pairtree,
  102. nsc['fcrepo'].Resource,
  103. nsc['fcrepo'].Version,
  104. nsc['ldp'].BasicContainer,
  105. nsc['ldp'].Container,
  106. nsc['ldp'].DirectContainer,
  107. nsc['ldp'].Resource,
  108. nsc['ldp'].RDFSource,
  109. nsc['ldp'].NonRDFSource,
  110. }
  111. """RDF types that don't get versioned."""
  112. _cached_attrs = (
  113. '_imr',
  114. '_metadata',
  115. '_version_info',
  116. '_is_stored',
  117. '_types',
  118. '_ldp_types',
  119. )
  120. """
  121. Attributes cached from the store.
  122. These are used by setters and can be cleared with :py:meth:`_clear_cache`.
  123. """
  124. ## MAGIC METHODS ##
  125. def __init__(self, uid, repr_opts={}, provided_imr=None, **kwargs):
  126. """
  127. Instantiate an in-memory LDP resource.
  128. :param str uid: uid of the resource. If None (must be explicitly
  129. set) it refers to the root node. It can also be the full URI or URN,
  130. in which case it will be converted.
  131. :param dict repr_opts: Options used to retrieve the IMR. See
  132. `parse_rfc7240` for format details.
  133. :param str provided_imr: RDF data provided by the client in
  134. operations such as `PUT` or `POST`, serialized as a string. This sets
  135. the `provided_imr` property.
  136. """
  137. self.uid = (
  138. rdfly.uri_to_uid(uid) if isinstance(uid, URIRef) else uid)
  139. self.uri = nsc['fcres'][uid]
  140. # @FIXME Not ideal, should separate app-context dependent functions in
  141. # a different toolbox.
  142. self.tbox = 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 = Imr(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, Imr):
  221. raise TypeError('Provided metadata is not an Imr 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_gr = Graph(identifier=self.uri)
  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_gr.add(t)
  242. return out_gr
  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 = Imr(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 = set(
  339. self.provided_imr | self._containment_rel(create))
  340. self.modify(ev_type, remove_trp, add_trp)
  341. #self.imr = add_trp
  342. return ev_type
  343. def bury(self, inbound, tstone_pointer=None):
  344. """
  345. Delete a single resource and create a tombstone.
  346. :param bool inbound: Whether inbound relationships are
  347. removed. If ``False``, resources will keep referring
  348. to the deleted resource; their link will point to a tombstone
  349. (which will raise a ``TombstoneError`` in the Python API or a
  350. ``410 Gone`` in the LDP API).
  351. :param rdflib.URIRef tstone_pointer: If set to a URI, this creates a
  352. pointer to the tombstone of the resource that used to contain the
  353. deleted resource. Otherwise the deleted resource becomes a
  354. tombstone.
  355. """
  356. logger.info('Burying resource {}'.format(self.uid))
  357. # ldp:Resource is also used in rdfly.ask_rsrc_exists.
  358. remove_trp = {
  359. (nsc['fcrepo'].uid, nsc['rdf'].type, nsc['ldp'].Resource)
  360. }
  361. if tstone_pointer:
  362. add_trp = {
  363. (self.uri, nsc['fcsystem'].tombstone, tstone_pointer)}
  364. else:
  365. add_trp = {
  366. (self.uri, RDF.type, nsc['fcsystem'].Tombstone),
  367. (self.uri, nsc['fcsystem'].buried, thread_env.timestamp_term),
  368. }
  369. # Bury descendants.
  370. from lakesuperior.model.ldp.ldp_factory import LdpFactory
  371. for desc_uri in rdfly.get_descendants(self.uid):
  372. try:
  373. desc_rsrc = LdpFactory.from_stored(
  374. env.app_globals.rdfly.uri_to_uid(desc_uri),
  375. repr_opts={'incl_children' : False})
  376. except (TombstoneError, ResourceNotExistsError):
  377. continue
  378. desc_rsrc.bury(inbound, tstone_pointer=self.uri)
  379. # Cut inbound relationships
  380. if inbound:
  381. for ib_rsrc_uri in self.imr[ : : self.uri]:
  382. remove_trp = {(ib_rsrc_uri, None, self.uri)}
  383. ib_rsrc = Ldpr(ib_rsrc_uri)
  384. # To preserve inbound links in history, create a snapshot
  385. ib_rsrc.create_version()
  386. ib_rsrc.modify(RES_UPDATED, remove_trp)
  387. self.modify(RES_DELETED, remove_trp, add_trp)
  388. return RES_DELETED
  389. def forget(self, inbound=True):
  390. """
  391. Remove all traces of a resource and versions.
  392. """
  393. logger.info('Forgetting resource {}'.format(self.uid))
  394. rdfly.forget_rsrc(self.uid, inbound)
  395. return RES_DELETED
  396. def resurrect(self):
  397. """
  398. Resurrect a resource from a tombstone.
  399. """
  400. remove_trp = {
  401. (self.uri, nsc['rdf'].type, nsc['fcsystem'].Tombstone),
  402. (self.uri, nsc['fcsystem'].tombstone, None),
  403. (self.uri, nsc['fcsystem'].buried, None),
  404. }
  405. add_trp = {
  406. (self.uri, nsc['rdf'].type, nsc['ldp'].Resource),
  407. }
  408. self.modify(RES_CREATED, remove_trp, add_trp)
  409. # Resurrect descendants.
  410. from lakesuperior.model.ldp.ldp_factory import LdpFactory
  411. descendants = env.app_globals.rdfly.get_descendants(self.uid)
  412. for desc_uri in descendants:
  413. LdpFactory.from_stored(
  414. rdfly.uri_to_uid(desc_uri), strict=False).resurrect()
  415. return self.uri
  416. def create_version(self, ver_uid=None):
  417. """
  418. Create a new version of the resource.
  419. **Note:** This creates an event only for the resource being updated
  420. (due to the added `hasVersion` triple and possibly to the
  421. ``hasVersions`` one) but not for the version being created.
  422. :param str ver_uid: Version UID. If already existing, a new version UID
  423. is minted.
  424. """
  425. if not ver_uid or ver_uid in self.version_uids:
  426. ver_uid = str(uuid4())
  427. # Create version resource from copying the current state.
  428. logger.info(
  429. 'Creating version snapshot {} for resource {}.'.format(
  430. ver_uid, self.uid))
  431. ver_add_gr = set()
  432. vers_uid = '{}/{}'.format(self.uid, VERS_CONT_LABEL)
  433. ver_uid = '{}/{}'.format(vers_uid, ver_uid)
  434. ver_uri = nsc['fcres'][ver_uid]
  435. ver_add_gr.add((ver_uri, RDF.type, nsc['fcrepo'].Version))
  436. for t in self.imr:
  437. if (
  438. t[1] == RDF.type and t[2] in self._ignore_version_types
  439. ) or t[1] in self._ignore_version_preds:
  440. pass
  441. else:
  442. ver_add_gr.add((
  443. self.tbox.replace_term_domain(t[0], self.uri, ver_uri),
  444. t[1], t[2]))
  445. rdfly.modify_rsrc(ver_uid, add_trp=ver_add_gr)
  446. # Update resource admin data.
  447. rsrc_add_gr = {
  448. (self.uri, nsc['fcrepo'].hasVersion, ver_uri),
  449. (self.uri, nsc['fcrepo'].hasVersions, nsc['fcres'][vers_uid]),
  450. }
  451. self.modify(RES_UPDATED, add_trp=rsrc_add_gr)
  452. return ver_uid
  453. def revert_to_version(self, ver_uid, backup=True):
  454. """
  455. Revert to a previous version.
  456. :param str ver_uid: Version UID.
  457. :param boolean backup: Whether to create a backup snapshot. Default is
  458. True.
  459. """
  460. # Create a backup snapshot.
  461. if backup:
  462. self.create_version()
  463. ver_gr = rdfly.get_imr(
  464. self.uid, ver_uid=ver_uid, incl_children=False)
  465. self.provided_imr = Imr(uri=self.uri)
  466. for t in ver_gr:
  467. if not self._is_trp_managed(t):
  468. self.provided_imr.add((self.uri, t[1], t[2]))
  469. # @TODO Check individual objects: if they are repo-managed URIs
  470. # and not existing or tombstones, they are not added.
  471. return self.create_or_replace(create_only=False)
  472. def check_mgd_terms(self, gr):
  473. """
  474. Check whether server-managed terms are in a RDF payload.
  475. :param SimpleGraph gr: The graph to validate.
  476. """
  477. offending_subjects = gr.terms_by_type('s') & srv_mgd_subjects
  478. if offending_subjects:
  479. if self.handling == 'strict':
  480. raise ServerManagedTermError(offending_subjects, 's')
  481. else:
  482. gr_set = set(gr)
  483. for s in offending_subjects:
  484. logger.info('Removing offending subj: {}'.format(s))
  485. for t in gr_set:
  486. if t[0] == s:
  487. gr.remove(t)
  488. offending_predicates = gr.terms_by_type('p') & srv_mgd_predicates
  489. # Allow some predicates if the resource is being created.
  490. if offending_predicates:
  491. if self.handling == 'strict':
  492. raise ServerManagedTermError(offending_predicates, 'p')
  493. else:
  494. gr_set = set(gr)
  495. for p in offending_predicates:
  496. logger.info('Removing offending pred: {}'.format(p))
  497. for t in gr_set:
  498. if t[1] == p:
  499. gr.remove(t)
  500. types = {t[2] for t in gr if t[1] == RDF.type}
  501. offending_types = types & srv_mgd_types
  502. if not self.is_stored:
  503. offending_types -= self.smt_allow_on_create
  504. if offending_types:
  505. if self.handling == 'strict':
  506. raise ServerManagedTermError(offending_types, 't')
  507. else:
  508. for to in offending_types:
  509. logger.info('Removing offending type: {}'.format(to))
  510. gr.remove_triples((None, RDF.type, to))
  511. #logger.debug('Sanitized graph: {}'.format(gr.serialize(
  512. # format='turtle').decode('utf-8')))
  513. return gr
  514. def sparql_delta(self, qry_str):
  515. """
  516. Calculate the delta obtained by a SPARQL Update operation.
  517. This is a critical component of the SPARQL update prcess and does a
  518. couple of things:
  519. 1. It ensures that no resources outside of the subject of the request
  520. are modified (e.g. by variable subjects)
  521. 2. It verifies that none of the terms being modified is server managed.
  522. This method extracts an in-memory copy of the resource and performs the
  523. query on that once it has checked if any of the server managed terms is
  524. in the delta. If it is, it raises an exception.
  525. NOTE: This only checks if a server-managed term is effectively being
  526. modified. If a server-managed term is present in the query but does not
  527. cause any change in the updated resource, no error is raised.
  528. :rtype: tuple(rdflib.Graph)
  529. :return: Remove and add graphs. These can be used
  530. with ``BaseStoreLayout.update_resource`` and/or recorded as separate
  531. events in a provenance tracking system.
  532. """
  533. logger.debug('Provided SPARQL query: {}'.format(qry_str))
  534. # Workaround for RDFLib bug. See
  535. # https://github.com/RDFLib/rdflib/issues/824
  536. qry_str = (
  537. re.sub('<#([^>]+)>', '<{}#\\1>'.format(self.uri), qry_str)
  538. .replace('<>', '<{}>'.format(self.uri)))
  539. pre_gr = self.imr.graph
  540. post_rdfgr = Graph(identifier=self.uri)
  541. post_rdfgr += pre_gr
  542. post_rdfgr.update(qry_str)
  543. post_gr = SimpleGraph(data=set(post_rdfgr))
  544. # FIXME Fix and use SimpleGraph's native subtraction operation.
  545. remove_gr = self.check_mgd_terms(SimpleGraph(pre_gr.data - post_gr.data))
  546. add_gr = self.check_mgd_terms(SimpleGraph(post_gr.data - pre_gr.data))
  547. return remove_gr, add_gr
  548. ## PROTECTED METHODS ##
  549. def _is_trp_managed(self, t):
  550. """
  551. Whether a triple is server-managed.
  552. :param tuple t: Triple as a 3-tuple of terms.
  553. :rtype: boolean
  554. """
  555. return t[1] in srv_mgd_predicates or (
  556. t[1] == RDF.type and t[2] in srv_mgd_types)
  557. def modify(
  558. self, ev_type, remove_trp=set(), add_trp=set()):
  559. """
  560. Low-level method to modify a graph for a single resource.
  561. This is a crucial point for messaging. Any write operation on the RDF
  562. store that needs to be notified should be performed by invoking this
  563. method.
  564. :param ev_type: The type of event (create, update,
  565. delete) or None. In the latter case, no notification is sent.
  566. :type ev_type: str or None
  567. :param set remove_trp: Triples to be removed.
  568. # Add metadata.
  569. :param set add_trp: Triples to be added.
  570. """
  571. rdfly.modify_rsrc(self.uid, remove_trp, add_trp)
  572. self._clear_cache()
  573. if (
  574. ev_type is not None and
  575. env.app_globals.config['application'].get('messaging')):
  576. logger.debug(f'Enqueuing message for {self.uid}')
  577. self._enqueue_msg(ev_type, remove_trp, add_trp)
  578. def _clear_cache(self):
  579. """
  580. Clear stale model attributes.
  581. This method removes class members populated with data pulled from the
  582. store that may have become stale after a resource update.
  583. """
  584. for attr in self._cached_attrs:
  585. try:
  586. delattr(self, attr)
  587. except AttributeError:
  588. pass
  589. def _enqueue_msg(self, ev_type, remove_trp=None, add_trp=None):
  590. """
  591. Compose a message about a resource change.
  592. The message is enqueued for asynchronous processing.
  593. :param str ev_type: The event type. See global constants.
  594. :param set remove_trp: Triples removed. Only used if the
  595. """
  596. try:
  597. rsrc_type = tuple(str(t) for t in self.types)
  598. actor = self.metadata.value(nsc['fcrepo'].createdBy)
  599. except (ResourceNotExistsError, TombstoneError):
  600. rsrc_type = set()
  601. actor = None
  602. for t in add_trp:
  603. if t[1] == RDF.type:
  604. rsrc_type.add(t[2])
  605. elif actor is None and t[1] == nsc['fcrepo'].createdBy:
  606. actor = t[2]
  607. env.app_globals.changelog.append((set(remove_trp), set(add_trp), {
  608. 'ev_type': ev_type,
  609. 'timestamp': thread_env.timestamp.format(),
  610. 'rsrc_type': rsrc_type,
  611. 'actor': actor,
  612. }))
  613. def _check_ref_int(self, config):
  614. """
  615. Check referential integrity of a resource.
  616. :param str config: If set to ``strict``, a
  617. :class:`lakesuperior.exceptions.RefIntViolationError` is raised.
  618. Otherwise, the violation is simply logged.
  619. """
  620. remove_set = set()
  621. for trp in self.provided_imr:
  622. o = trp[2]
  623. if(
  624. isinstance(o, URIRef) and
  625. str(o).startswith(nsc['fcres']) and
  626. urldefrag(o).url.rstrip('/') != str(self.uri)):
  627. obj_uid = rdfly.uri_to_uid(o)
  628. if not rdfly.ask_rsrc_exists(obj_uid):
  629. if config == 'strict':
  630. raise RefIntViolationError(obj_uid)
  631. else:
  632. # Gather invalid object to sanitize.
  633. remove_set.add(o)
  634. # Remove invalid triples.
  635. for obj in remove_set:
  636. logger.info(
  637. 'Removing link to non-existent repo resource: {}'
  638. .format(obj))
  639. self.provided_imr.remove_triples((None, None, obj))
  640. def _add_srv_mgd_triples(self, create=False):
  641. """
  642. Add server-managed triples to a provided IMR.
  643. :param create: Whether the resource is being created.
  644. """
  645. # Base LDP types.
  646. self.provided_imr.add(
  647. [(self.uri, RDF.type, t) for t in self.base_types]
  648. )
  649. # Create and modify timestamp.
  650. if create:
  651. self.provided_imr.set((
  652. self.uri, nsc['fcrepo'].created, thread_env.timestamp_term))
  653. self.provided_imr.set((
  654. self.uri, nsc['fcrepo'].createdBy, self.DEFAULT_USER))
  655. else:
  656. self.provided_imr.set((
  657. self.uri, nsc['fcrepo'].created,
  658. self.metadata.value(nsc['fcrepo'].created)))
  659. self.provided_imr.set((
  660. self.uri, nsc['fcrepo'].createdBy,
  661. self.metadata.value(nsc['fcrepo'].createdBy)))
  662. self.provided_imr.set((
  663. self.uri, nsc['fcrepo'].lastModified, thread_env.timestamp_term))
  664. self.provided_imr.set((
  665. self.uri, nsc['fcrepo'].lastModifiedBy, self.DEFAULT_USER))
  666. def _containment_rel(self, create, ignore_type=True):
  667. """Find the closest parent in the path indicated by the uid and
  668. establish a containment triple.
  669. Check the path-wise parent of the new resource. If it exists, add the
  670. containment relationship with this UID. Otherwise, create a container
  671. resource as the parent.
  672. This function may recurse up the path tree until an existing container
  673. is found.
  674. E.g. if only fcres:/a exists:
  675. - If ``fcres:/a/b/c/d`` is being created, a becomes container of
  676. ``fcres:/a/b/c/d``. Also, containers are created for fcres:a/b and
  677. ``fcres:/a/b/c``.
  678. - If ``fcres:/e`` is being created, the root node becomes container of
  679. ``fcres:/e``.
  680. :param bool create: Whether the resource is being created. If false,
  681. the parent container is not updated.
  682. "param bool ignore_type: If False (the default), an exception is raised
  683. if trying to create a resource under a non-container. This can be
  684. overridden in special cases (e.g. when migrating a repository in which
  685. a LDP-NR has "children" under ``fcr:versions``) by setting this to
  686. True.
  687. """
  688. from lakesuperior.model.ldp.ldp_factory import LdpFactory
  689. if '/' in self.uid.lstrip('/'):
  690. # Traverse up the hierarchy to find the parent.
  691. path_components = self.uid.lstrip('/').split('/')
  692. cnd_parent_uid = '/' + '/'.join(path_components[:-1])
  693. if rdfly.ask_rsrc_exists(cnd_parent_uid):
  694. parent_rsrc = LdpFactory.from_stored(cnd_parent_uid)
  695. if (
  696. not ignore_type
  697. and nsc['ldp'].Container not in parent_rsrc.types):
  698. raise InvalidResourceError(
  699. cnd_parent_uid, 'Parent {} is not a container.')
  700. parent_uid = cnd_parent_uid
  701. else:
  702. parent_rsrc = LdpFactory.new_container(cnd_parent_uid)
  703. # This will trigger this method again and recurse until an
  704. # existing container or the root node is reached.
  705. parent_rsrc.create_or_replace()
  706. parent_uid = parent_rsrc.uid
  707. else:
  708. parent_uid = ROOT_UID
  709. parent_rsrc = LdpFactory.from_stored(
  710. parent_uid, repr_opts={'incl_children': False}, handling='none')
  711. # Only update parent if the resource is new.
  712. if create:
  713. add_gr = Graph()
  714. add_gr.add(
  715. (nsc['fcres'][parent_uid], nsc['ldp'].contains, self.uri))
  716. parent_rsrc.modify(RES_UPDATED, add_trp=add_gr)
  717. # Direct or indirect container relationship.
  718. return self._add_ldp_dc_ic_rel(parent_rsrc)
  719. def _add_ldp_dc_ic_rel(self, cont_rsrc):
  720. """
  721. Add relationship triples from a parent direct or indirect container.
  722. :param rdflib.resource.Resouce cont_rsrc: The container resource.
  723. """
  724. cont_p = cont_rsrc.metadata.terms_by_type('p')
  725. logger.info('Checking direct or indirect containment.')
  726. logger.debug('Parent predicates: {}'.format(cont_p))
  727. add_trp = {(self.uri, nsc['fcrepo'].hasParent, cont_rsrc.uri)}
  728. if self.MBR_RSRC_URI in cont_p and self.MBR_REL_URI in cont_p:
  729. from lakesuperior.model.ldp.ldp_factory import LdpFactory
  730. s = cont_rsrc.metadata.value(self.MBR_RSRC_URI)
  731. p = cont_rsrc.metadata.value(self.MBR_REL_URI)
  732. if nsc['ldp'].DirectContainer in cont_rsrc.ldp_types:
  733. logger.info('Parent is a direct container.')
  734. logger.debug('Creating DC triples.')
  735. o = self.uri
  736. elif nsc['ldp'].IndirectContainer in cont_rsrc.ldp_types:
  737. logger.info('Parent is an indirect container.')
  738. cont_rel_uri = cont_rsrc.metadata.value(self.INS_CNT_REL_URI)
  739. o = self.provided_imr.value(cont_rel_uri)
  740. logger.debug('Target URI: {}'.format(o))
  741. logger.debug('Creating IC triples.')
  742. target_rsrc = LdpFactory.from_stored(rdfly.uri_to_uid(s))
  743. target_rsrc.modify(RES_UPDATED, add_trp={(s, p, o)})
  744. return add_trp