ldpr.py 31 KB

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