ldpr.py 32 KB

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