import time
import json


def retrieve_from_stash(request, key, timeout, default_value, min_count=None, retain=False):
  """Retrieve the set of reports for a given report ID.

  This will extract either the set of reports, credentials, or request count
  from the stash (depending on the key passed in) and return it encoded as JSON.

  When retrieving reports, this will not return any reports until min_count
  reports have been received.

  If timeout seconds elapse before the requested data can be found in the stash,
  or before at least min_count reports are received, default_value will be
  returned instead."""
  t0 = time.time()
  while time.time() - t0 < timeout:
    time.sleep(0.5)
    with request.server.stash.lock:
      value = request.server.stash.take(key=key)
      if value is not None:
        have_sufficient_reports = (min_count is None or len(value) >= min_count)
        if retain or not have_sufficient_reports:
          request.server.stash.put(key=key, value=value)
        if have_sufficient_reports:
          return json.dumps(value)

  return default_value