resource.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. import logging
  2. from functools import wraps
  3. from itertools import groupby
  4. from multiprocessing import Process
  5. from threading import Lock, Thread
  6. import arrow
  7. from rdflib import Literal
  8. from rdflib.namespace import XSD
  9. from lakesuperior.config_parser import config
  10. from lakesuperior.exceptions import (
  11. InvalidResourceError, ResourceNotExistsError, TombstoneError)
  12. from lakesuperior import env, thread_env
  13. from lakesuperior.globals import RES_DELETED, RES_UPDATED
  14. from lakesuperior.model.ldp.ldp_factory import LDP_NR_TYPE, LdpFactory
  15. logger = logging.getLogger(__name__)
  16. __doc__ = """
  17. Primary API for resource manipulation.
  18. Quickstart::
  19. >>> # First import default configuration and globals—only done once.
  20. >>> import lakesuperior.default_env
  21. >>> from lakesuperior.api import resource
  22. >>> # Get root resource.
  23. >>> rsrc = resource.get('/')
  24. >>> # Dump graph.
  25. >>> set(rsrc.imr)
  26. {(rdflib.term.URIRef('info:fcres/'),
  27. rdflib.term.URIRef('http://purl.org/dc/terms/title'),
  28. rdflib.term.Literal('Repository Root')),
  29. (rdflib.term.URIRef('info:fcres/'),
  30. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  31. rdflib.term.URIRef('http://fedora.info/definitions/v4/repository#Container')),
  32. (rdflib.term.URIRef('info:fcres/'),
  33. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  34. rdflib.term.URIRef('http://fedora.info/definitions/v4/repository#RepositoryRoot')),
  35. (rdflib.term.URIRef('info:fcres/'),
  36. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  37. rdflib.term.URIRef('http://fedora.info/definitions/v4/repository#Resource')),
  38. (rdflib.term.URIRef('info:fcres/'),
  39. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  40. rdflib.term.URIRef('http://www.w3.org/ns/ldp#BasicContainer')),
  41. (rdflib.term.URIRef('info:fcres/'),
  42. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  43. rdflib.term.URIRef('http://www.w3.org/ns/ldp#Container')),
  44. (rdflib.term.URIRef('info:fcres/'),
  45. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  46. rdflib.term.URIRef('http://www.w3.org/ns/ldp#RDFSource'))}
  47. """
  48. def transaction(write=False):
  49. """
  50. Handle atomic operations in a store.
  51. This wrapper ensures that a write operation is performed atomically. It
  52. also takes care of sending a message for each resource changed in the
  53. transaction.
  54. ALL write operations on the LDP-RS and LDP-NR stores go through this
  55. wrapper.
  56. """
  57. def _transaction_deco(fn):
  58. @wraps(fn)
  59. def _wrapper(*args, **kwargs):
  60. # Mark transaction begin timestamp. This is used for create and
  61. # update timestamps on resources.
  62. thread_env.timestamp = arrow.utcnow()
  63. thread_env.timestamp_term = Literal(
  64. thread_env.timestamp, datatype=XSD.dateTime)
  65. with env.app_globals.rdf_store.txn_ctx(write):
  66. ret = fn(*args, **kwargs)
  67. if len(env.app_globals.changelog):
  68. job = Thread(target=_process_queue)
  69. job.start()
  70. delattr(thread_env, 'timestamp')
  71. delattr(thread_env, 'timestamp_term')
  72. return ret
  73. return _wrapper
  74. return _transaction_deco
  75. def _process_queue():
  76. """
  77. Process the message queue on a separate thread.
  78. """
  79. lock = Lock()
  80. lock.acquire()
  81. while len(env.app_globals.changelog):
  82. _send_event_msg(*env.app_globals.changelog.popleft())
  83. lock.release()
  84. def _send_event_msg(remove_trp, add_trp, metadata):
  85. """
  86. Send messages about a changed LDPR.
  87. A single LDPR message packet can contain multiple resource subjects, e.g.
  88. if the resource graph contains hash URIs or even other subjects. This
  89. method groups triples by subject and sends a message for each of the
  90. subjects found.
  91. """
  92. # Group delta triples by subject.
  93. remove_grp = groupby(remove_trp, lambda x : x[0])
  94. remove_dict = {k[0]: k[1] for k in remove_grp}
  95. add_grp = groupby(add_trp, lambda x : x[0])
  96. add_dict = {k[0]: k[1] for k in add_grp}
  97. subjects = set(remove_dict.keys()) | set(add_dict.keys())
  98. for rsrc_uri in subjects:
  99. logger.debug('Processing event for subject: {}'.format(rsrc_uri))
  100. env.app_globals.messenger.send(rsrc_uri, **metadata)
  101. ### API METHODS ###
  102. @transaction()
  103. def exists(uid):
  104. """
  105. Return whether a resource exists (is stored) in the repository.
  106. :param string uid: Resource UID.
  107. """
  108. try:
  109. exists = LdpFactory.from_stored(uid).is_stored
  110. except ResourceNotExistsError:
  111. exists = False
  112. return exists
  113. @transaction()
  114. def get_metadata(uid):
  115. """
  116. Get metadata (admin triples) of an LDPR resource.
  117. :param string uid: Resource UID.
  118. """
  119. return LdpFactory.from_stored(uid).metadata
  120. @transaction()
  121. def get(uid, repr_options={}):
  122. """
  123. Get an LDPR resource.
  124. The resource comes preloaded with user data and metadata as indicated by
  125. the `repr_options` argument. Any further handling of this resource is done
  126. outside of a transaction.
  127. :param string uid: Resource UID.
  128. :param repr_options: (dict(bool)) Representation options. This is a dict
  129. that is unpacked downstream in the process. The default empty dict
  130. results in default values. The accepted dict keys are:
  131. - incl_inbound: include inbound references. Default: False.
  132. - incl_children: include children URIs. Default: True.
  133. - embed_children: Embed full graph of all child resources. Default: False
  134. """
  135. rsrc = LdpFactory.from_stored(uid, repr_opts=repr_options)
  136. # Load graph before leaving the transaction.
  137. rsrc.imr
  138. return rsrc
  139. @transaction()
  140. def get_version_info(uid):
  141. """
  142. Get version metadata (fcr:versions).
  143. """
  144. return LdpFactory.from_stored(uid).version_info
  145. @transaction()
  146. def get_version(uid, ver_uid):
  147. """
  148. Get version metadata (fcr:versions).
  149. """
  150. return LdpFactory.from_stored(uid).get_version(ver_uid)
  151. @transaction(True)
  152. def create(parent, slug=None, **kwargs):
  153. r"""
  154. Mint a new UID and create a resource.
  155. The UID is computed from a given parent UID and a "slug", a proposed path
  156. relative to the parent. The application will attempt to use the suggested
  157. path but it may use a different one if a conflict with an existing resource
  158. arises.
  159. :param str parent: UID of the parent resource.
  160. :param str slug: Tentative path relative to the parent UID.
  161. :param \*\*kwargs: Other parameters are passed to the
  162. :py:meth:`~lakesuperior.model.ldp.ldp_factory.LdpFactory.from_provided`
  163. method.
  164. :rtype: tuple(str, lakesuperior.model.ldp.ldpr.Ldpr)
  165. :return: A tuple of:
  166. 1. Event type (str): whether the resource was created or updated.
  167. 2. Resource (lakesuperior.model.ldp.ldpr.Ldpr): The new or updated resource.
  168. """
  169. uid = LdpFactory.mint_uid(parent, slug)
  170. logger.debug('Minted UID for new resource: {}'.format(uid))
  171. rsrc = LdpFactory.from_provided(uid, **kwargs)
  172. rsrc.create_or_replace(create_only=True)
  173. return rsrc
  174. @transaction(True)
  175. def create_or_replace(uid, **kwargs):
  176. r"""
  177. Create or replace a resource with a specified UID.
  178. :param string uid: UID of the resource to be created or updated.
  179. :param \*\*kwargs: Other parameters are passed to the
  180. :py:meth:`~lakesuperior.model.ldp.ldp_factory.LdpFactory.from_provided`
  181. method.
  182. :rtype: tuple(str, lakesuperior.model.ldp.ldpr.Ldpr)
  183. :return: A tuple of:
  184. 1. Event type (str): whether the resource was created or updated.
  185. 2. Resource (lakesuperior.model.ldp.ldpr.Ldpr): The new or updated resource.
  186. """
  187. rsrc = LdpFactory.from_provided(uid, **kwargs)
  188. return rsrc.create_or_replace(), rsrc
  189. @transaction(True)
  190. def update(uid, update_str, is_metadata=False):
  191. """
  192. Update a resource with a SPARQL-Update string.
  193. :param string uid: Resource UID.
  194. :param string update_str: SPARQL-Update statements.
  195. :param bool is_metadata: Whether the resource metadata are being updated.
  196. :raise InvalidResourceError: If ``is_metadata`` is False and the resource
  197. being updated is a LDP-NR.
  198. """
  199. # FCREPO is lenient here and Hyrax requires it.
  200. rsrc = LdpFactory.from_stored(uid, handling='lenient')
  201. if LDP_NR_TYPE in rsrc.ldp_types and not is_metadata:
  202. raise InvalidResourceError(
  203. 'Cannot use this method to update an LDP-NR content.')
  204. delta = rsrc.sparql_delta(update_str)
  205. rsrc.modify(RES_UPDATED, *delta)
  206. return rsrc
  207. @transaction(True)
  208. def update_delta(uid, remove_trp, add_trp):
  209. """
  210. Update a resource graph (LDP-RS or LDP-NR) with sets of add/remove triples.
  211. A set of triples to add and/or a set of triples to remove may be provided.
  212. :param string uid: Resource UID.
  213. :param set(tuple(rdflib.term.Identifier)) remove_trp: Triples to
  214. remove, as 3-tuples of RDFLib terms.
  215. :param set(tuple(rdflib.term.Identifier)) add_trp: Triples to
  216. add, as 3-tuples of RDFLib terms.
  217. """
  218. rsrc = LdpFactory.from_stored(uid)
  219. remove_trp = rsrc.check_mgd_terms(remove_trp)
  220. add_trp = rsrc.check_mgd_terms(add_trp)
  221. return rsrc.modify(RES_UPDATED, remove_trp, add_trp)
  222. @transaction(True)
  223. def create_version(uid, ver_uid):
  224. """
  225. Create a resource version.
  226. :param string uid: Resource UID.
  227. :param string ver_uid: Version UID to be appended to the resource URI.
  228. NOTE: this is a "slug", i.e. the version URI is not guaranteed to be the
  229. one indicated.
  230. :rtype: str
  231. :return: Version UID.
  232. """
  233. return LdpFactory.from_stored(uid).create_version(ver_uid)
  234. @transaction(True)
  235. def delete(uid, soft=True, inbound=True):
  236. """
  237. Delete a resource.
  238. :param string uid: Resource UID.
  239. :param bool soft: Whether to perform a soft-delete and leave a
  240. tombstone resource, or wipe any memory of the resource.
  241. """
  242. # If referential integrity is enforced, grab all inbound relationships
  243. # to break them.
  244. refint = env.app_globals.rdfly.config['referential_integrity']
  245. inbound = True if refint else inbound
  246. repr_opts = {'incl_inbound' : True} if inbound else {}
  247. rsrc = LdpFactory.from_stored(uid, repr_opts, strict=soft)
  248. if soft:
  249. return rsrc.bury(inbound)
  250. else:
  251. return rsrc.forget(inbound)
  252. @transaction(True)
  253. def revert_to_version(uid, ver_uid):
  254. """
  255. Restore a resource to a previous version state.
  256. :param str uid: Resource UID.
  257. :param str ver_uid: Version UID.
  258. """
  259. return LdpFactory.from_stored(uid).revert_to_version(ver_uid)
  260. @transaction(True)
  261. def resurrect(uid):
  262. """
  263. Reinstate a buried (soft-deleted) resource.
  264. :param str uid: Resource UID.
  265. """
  266. try:
  267. rsrc = LdpFactory.from_stored(uid)
  268. except TombstoneError as e:
  269. if e.uid != uid:
  270. raise
  271. else:
  272. return LdpFactory.from_stored(uid, strict=False).resurrect()
  273. else:
  274. raise InvalidResourceError(
  275. uid, msg='Resource {} is not dead.'.format(uid))