ldpr.py 30 KB

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