resource.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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.env import env
  13. from lakesuperior.globals import RES_DELETED
  14. from lakesuperior.model.ldp_factory import LDP_NR_TYPE, LdpFactory
  15. from lakesuperior.store.ldp_rs.lmdb_store import TxnManager
  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. >>> import lakesuperior.default_env
  22. >>> from lakesuperior.api import resource
  23. >>> # Get root resource.
  24. >>> rsrc = resource.get('/')
  25. >>> # Dump graph.
  26. >>> set(rsrc.imr)
  27. {(rdflib.term.URIRef('info:fcres/'),
  28. rdflib.term.URIRef('http://purl.org/dc/terms/title'),
  29. rdflib.term.Literal('Repository Root')),
  30. (rdflib.term.URIRef('info:fcres/'),
  31. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  32. rdflib.term.URIRef('http://fedora.info/definitions/v4/repository#Container')),
  33. (rdflib.term.URIRef('info:fcres/'),
  34. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  35. rdflib.term.URIRef('http://fedora.info/definitions/v4/repository#RepositoryRoot')),
  36. (rdflib.term.URIRef('info:fcres/'),
  37. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  38. rdflib.term.URIRef('http://fedora.info/definitions/v4/repository#Resource')),
  39. (rdflib.term.URIRef('info:fcres/'),
  40. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  41. rdflib.term.URIRef('http://www.w3.org/ns/ldp#BasicContainer')),
  42. (rdflib.term.URIRef('info:fcres/'),
  43. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  44. rdflib.term.URIRef('http://www.w3.org/ns/ldp#Container')),
  45. (rdflib.term.URIRef('info:fcres/'),
  46. rdflib.term.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
  47. rdflib.term.URIRef('http://www.w3.org/ns/ldp#RDFSource'))}
  48. """
  49. def transaction(write=False):
  50. """
  51. Handle atomic operations in a store.
  52. This wrapper ensures that a write operation is performed atomically. It
  53. also takes care of sending a message for each resource changed in the
  54. transaction.
  55. ALL write operations on the LDP-RS and LDP-NR stores go through this
  56. wrapper.
  57. """
  58. def _transaction_deco(fn):
  59. @wraps(fn)
  60. def _wrapper(*args, **kwargs):
  61. # Mark transaction begin timestamp. This is used for create and
  62. # update timestamps on resources.
  63. env.timestamp = arrow.utcnow()
  64. env.timestamp_term = Literal(env.timestamp, datatype=XSD.dateTime)
  65. with TxnManager(env.app_globals.rdf_store, write=write) as txn:
  66. ret = fn(*args, **kwargs)
  67. if len(env.app_globals.changelog):
  68. job = Thread(target=process_queue)
  69. job.start()
  70. delattr(env, 'timestamp')
  71. delattr(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_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, **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. :meth:`LdpFactory.from_provided` method.
  163. :rtype: str
  164. :return: UID of the new resource.
  165. """
  166. uid = LdpFactory.mint_uid(parent, slug)
  167. logger.debug('Minted UID for new resource: {}'.format(uid))
  168. rsrc = LdpFactory.from_provided(uid, **kwargs)
  169. rsrc.create_or_replace(create_only=True)
  170. return uid
  171. @transaction(True)
  172. def create_or_replace(uid, stream=None, **kwargs):
  173. r"""
  174. Create or replace a resource with a specified UID.
  175. If the resource already exists, all user-provided properties of the
  176. existing resource are deleted. If the resource exists and the provided
  177. content is empty, an exception is raised (not sure why, but that's how
  178. FCREPO4 handles it).
  179. :param string uid: UID of the resource to be created or updated.
  180. :param BytesIO stream: Content stream. If empty, an empty container is
  181. created.
  182. :param \*\*kwargs: Other parameters are passed to the
  183. :meth:`LdpFactory.from_provided` method.
  184. :rtype: str
  185. :return: Event type: whether the resource was created or updated.
  186. """
  187. rsrc = LdpFactory.from_provided(uid, stream=stream, **kwargs)
  188. if not stream and rsrc.is_stored:
  189. raise InvalidResourceError(rsrc.uid,
  190. 'Resource {} already exists and no data set was provided.')
  191. return rsrc.create_or_replace()
  192. @transaction(True)
  193. def update(uid, update_str, is_metadata=False):
  194. """
  195. Update a resource with a SPARQL-Update string.
  196. :param string uid: Resource UID.
  197. :param string update_str: SPARQL-Update statements.
  198. :param bool is_metadata: Whether the resource metadata is being updated.
  199. If False, and the resource being updated is a LDP-NR, an error is
  200. raised.
  201. """
  202. rsrc = LdpFactory.from_stored(uid)
  203. if LDP_NR_TYPE in rsrc.ldp_types and not is_metadata:
  204. raise InvalidResourceError(uid)
  205. rsrc.sparql_update(update_str)
  206. return rsrc
  207. @transaction(True)
  208. def create_version(uid, ver_uid):
  209. """
  210. Create a resource version.
  211. :param string uid: Resource UID.
  212. :param string ver_uid: Version UID to be appended to the resource URI.
  213. NOTE: this is a "slug", i.e. the version URI is not guaranteed to be the
  214. one indicated.
  215. :rtype: str
  216. :return: Version UID.
  217. """
  218. return LdpFactory.from_stored(uid).create_version(ver_uid)
  219. @transaction(True)
  220. def delete(uid, soft=True):
  221. """
  222. Delete a resource.
  223. :param string uid: Resource UID.
  224. :param bool soft: Whether to perform a soft-delete and leave a
  225. tombstone resource, or wipe any memory of the resource.
  226. """
  227. # If referential integrity is enforced, grab all inbound relationships
  228. # to break them.
  229. refint = env.app_globals.rdfly.config['referential_integrity']
  230. inbound = True if refint else inbound
  231. repr_opts = {'incl_inbound' : True} if refint else {}
  232. children = env.app_globals.rdfly.get_descendants(uid)
  233. if soft:
  234. rsrc = LdpFactory.from_stored(uid, repr_opts)
  235. ret = rsrc.bury_rsrc(inbound)
  236. for child_uri in children:
  237. try:
  238. child_rsrc = LdpFactory.from_stored(
  239. env.app_globals.rdfly.uri_to_uid(child_uri),
  240. repr_opts={'incl_children' : False})
  241. except (TombstoneError, ResourceNotExistsError):
  242. continue
  243. child_rsrc.bury_rsrc(inbound, tstone_pointer=rsrc.uri)
  244. else:
  245. ret = env.app_globals.rdfly.forget_rsrc(uid, inbound)
  246. for child_uri in children:
  247. child_uid = env.app_globals.rdfly.uri_to_uid(child_uri)
  248. ret = env.app_globals.rdfly.forget_rsrc(child_uid, inbound)
  249. return ret
  250. @transaction(True)
  251. def resurrect(uid):
  252. """
  253. Reinstate a buried (soft-deleted) resource.
  254. :param str uid: Resource UID.
  255. """
  256. return LdpFactory.from_stored(uid).resurrect_rsrc()