ldpr.py 32 KB

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