ldpr.py 31 KB

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