resource.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 InvalidResourceError
  11. from lakesuperior.env import env
  12. from lakesuperior.globals import RES_DELETED
  13. from lakesuperior.model.ldp_factory import LDP_NR_TYPE, LdpFactory
  14. from lakesuperior.store.ldp_rs.lmdb_store import TxnManager
  15. logger = logging.getLogger(__name__)
  16. app_globals = env.app_globals
  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(app_globals.rdf_store, write=write) as txn:
  66. ret = fn(*args, **kwargs)
  67. if len(app_globals.changelog):
  68. job = Thread(target=process_queue)
  69. job.start()
  70. logger.debug('Deleting timestamp: {}'.format(getattr(env, 'timestamp')))
  71. delattr(env, 'timestamp')
  72. delattr(env, 'timestamp_term')
  73. return ret
  74. return _wrapper
  75. return _transaction_deco
  76. def process_queue():
  77. '''
  78. Process the message queue on a separate thread.
  79. '''
  80. lock = Lock()
  81. lock.acquire()
  82. while len(app_globals.changelog):
  83. send_event_msg(*app_globals.changelog.popleft())
  84. lock.release()
  85. def send_event_msg(remove_trp, add_trp, metadata):
  86. '''
  87. Break down delta triples, find subjects and send event message.
  88. '''
  89. remove_grp = groupby(remove_trp, lambda x : x[0])
  90. remove_dict = { k[0] : k[1] for k in remove_grp }
  91. add_grp = groupby(add_trp, lambda x : x[0])
  92. add_dict = { k[0] : k[1] for k in add_grp }
  93. subjects = set(remove_dict.keys()) | set(add_dict.keys())
  94. for rsrc_uri in subjects:
  95. logger.info('subject: {}'.format(rsrc_uri))
  96. app_globals.messenger.send
  97. ### API METHODS ###
  98. @transaction()
  99. def get(uid, repr_options={}):
  100. '''
  101. Get an LDPR resource.
  102. The resource comes preloaded with user data and metadata as indicated by
  103. the `repr_options` argument. Any further handling of this resource is done
  104. outside of a transaction.
  105. @param uid (string) Resource UID.
  106. @param repr_options (dict(bool)) Representation options. This is a dict
  107. that is unpacked downstream in the process. The default empty dict results
  108. in default values. The accepted dict keys are:
  109. - incl_inbound: include inbound references. Default: False.
  110. - incl_children: include children URIs. Default: True.
  111. - embed_children: Embed full graph of all child resources. Default: False
  112. '''
  113. rsrc = LdpFactory.from_stored(uid, repr_options)
  114. # Load graph before leaving the transaction.
  115. rsrc.imr
  116. return rsrc
  117. @transaction()
  118. def get_version_info(uid):
  119. '''
  120. Get version metadata (fcr:versions).
  121. '''
  122. return LdpFactory.from_stored(uid).version_info
  123. @transaction()
  124. def get_version(uid, ver_uid):
  125. '''
  126. Get version metadata (fcr:versions).
  127. '''
  128. return LdpFactory.from_stored(uid).get_version(ver_uid)
  129. @transaction(True)
  130. def create(parent, slug, **kwargs):
  131. '''
  132. Mint a new UID and create a resource.
  133. The UID is computed from a given parent UID and a "slug", a proposed path
  134. relative to the parent. The application will attempt to use the suggested
  135. path but it may use a different one if a conflict with an existing resource
  136. arises.
  137. @param parent (string) UID of the parent resource.
  138. @param slug (string) Tentative path relative to the parent UID.
  139. @param **kwargs Other parameters are passed to the
  140. LdpFactory.from_provided method. Please see the documentation for that
  141. method for explanation of individual parameters.
  142. @return string UID of the new resource.
  143. '''
  144. uid = LdpFactory.mint_uid(parent, slug)
  145. logger.debug('Minted UID for new resource: {}'.format(uid))
  146. rsrc = LdpFactory.from_provided(uid, **kwargs)
  147. rsrc.create_or_replace_rsrc(create_only=True)
  148. return uid
  149. @transaction(True)
  150. def create_or_replace(uid, stream=None, **kwargs):
  151. '''
  152. Create or replace a resource with a specified UID.
  153. If the resource already exists, all user-provided properties of the
  154. existing resource are deleted. If the resource exists and the provided
  155. content is empty, an exception is raised (not sure why, but that's how
  156. FCREPO4 handles it).
  157. @param uid (string) UID of the resource to be created or updated.
  158. @param stream (BytesIO) Content stream. If empty, an empty container is
  159. created.
  160. @param **kwargs Other parameters are passed to the
  161. LdpFactory.from_provided method. Please see the documentation for that
  162. method for explanation of individual parameters.
  163. @return string Event type: whether the resource was created or updated.
  164. '''
  165. rsrc = LdpFactory.from_provided(uid, stream=stream, **kwargs)
  166. if not stream and rsrc.is_stored:
  167. raise InvalidResourceError(rsrc.uid,
  168. 'Resource {} already exists and no data set was provided.')
  169. return rsrc.create_or_replace_rsrc()
  170. @transaction(True)
  171. def update(uid, update_str, is_metadata=False):
  172. '''
  173. Update a resource with a SPARQL-Update string.
  174. @param uid (string) Resource UID.
  175. @param update_str (string) SPARQL-Update statements.
  176. @param is_metadata (bool) Whether the resource metadata is being updated.
  177. If False, and the resource being updated is a LDP-NR, an error is raised.
  178. '''
  179. rsrc = LdpFactory.from_stored(uid)
  180. if LDP_NR_TYPE in rsrc.ldp_types:
  181. if is_metadata:
  182. rsrc.patch_metadata(update_str)
  183. else:
  184. raise InvalidResourceError(uid)
  185. else:
  186. rsrc.patch(update_str)
  187. return rsrc
  188. @transaction(True)
  189. def create_version(uid, ver_uid):
  190. '''
  191. Create a resource version.
  192. @param uid (string) Resource UID.
  193. @param ver_uid (string) Version UID to be appended to the resource URI.
  194. NOTE: this is a "slug", i.e. the version URI is not guaranteed to be the
  195. one indicated.
  196. @return string Version UID.
  197. '''
  198. return LdpFactory.from_stored(uid).create_version(ver_uid)
  199. @transaction(True)
  200. def delete(uid, soft=True):
  201. '''
  202. Delete a resource.
  203. @param uid (string) Resource UID.
  204. @param soft (bool) Whether to perform a soft-delete and leave a
  205. tombstone resource, or wipe any memory of the resource.
  206. '''
  207. # If referential integrity is enforced, grab all inbound relationships
  208. # to break them.
  209. refint = app_globals.rdfly.config['referential_integrity']
  210. inbound = True if refint else inbound
  211. repr_opts = {'incl_inbound' : True} if refint else {}
  212. children = app_globals.rdfly.get_descendants(uid)
  213. if soft:
  214. rsrc = LdpFactory.from_stored(uid, repr_opts)
  215. ret = rsrc.bury_rsrc(inbound)
  216. for child_uri in children:
  217. try:
  218. child_rsrc = LdpFactory.from_stored(
  219. app_globals.rdfly.uri_to_uid(child_uri),
  220. repr_opts={'incl_children' : False})
  221. except (TombstoneError, ResourceNotExistsError):
  222. continue
  223. child_rsrc.bury_rsrc(inbound, tstone_pointer=rsrc.uri)
  224. else:
  225. ret = app_globals.rdfly.forget_rsrc(uid, inbound)
  226. for child_uri in children:
  227. child_uid = app_globals.rdfly.uri_to_uid(child_uri)
  228. ret = app_globals.rdfly.forget_rsrc(child_uid, inbound)
  229. return ret
  230. @transaction(True)
  231. def resurrect(uid):
  232. '''
  233. Reinstate a buried (soft-deleted) resource.
  234. @param uid (string) Resource UID.
  235. '''
  236. return LdpFactory.from_stored(uid).resurrect_rsrc()