resource.py 12 KB

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