def update(self, doc, process=None):
        if process is None:
            pk = 'id'
            id = doc.id
            doc.synced = False
            set = doc
        elif process == UPDATE_PROCESS:
            if self.db.docs.find({'sid': doc.sid}).count() == 0:
                return self.insert(doc, synced=True)
            pk = 'sid'
            id = doc.sid
            doc.synced = not doc.merged() # must be commited if was merged
            doc.merged(False)
            set = {'tid': doc.tid, 'data': doc.data, 'user': doc.user,
                   'public': doc.public, 'synced': doc.synced}
        elif process == COMMIT_PROCESS:
            pk = 'id'
            id = doc.id
            doc.synced = True
            set = {'sid': doc.sid, 'tid': doc.tid, 'synced': doc.synced}
        else:
            raise DatabaseException('Incorrect update process')

        try:
            rs = self.db.docs.update({pk: id}, {'$set': set}, safe=True)
            assert rs['n'] == 1
        except Exception as e:
            raise DatabaseException(e)
        return doc
def _get_or_create_cached_value(self, key, getter, ttl=None):
        # happy path
        try:
            expiry, value = self._cache[key]
        except KeyError:
            pass
        else:
            if expiry is None or time.time() < expiry:
                logger.debug("Key %s from cache", key)
                return value
            logger.debug("Cache for key %s has expired", key)

        # get value
        value = getter()
        if ttl:
            expiry = time.time() + ttl
        else:
            expiry = None
        self._cache[key] = (expiry, value)
        logger.debug("Set cache for key %s", key)

        return value