Perform the compaction operation.  This reads in the bucket
    information from the database, builds a compacted bucket record,
    inserts that record in the appropriate place in the database, then
    removes outdated updates.

    :param db: A database handle for the Redis database.
    :param buck_key: A turnstile.limits.BucketKey instance containing
                     the bucket key.
    :param limit: The turnstile.limits.Limit object corresponding to
                  the bucket.

def compact_bucket(db, buck_key, limit):
    """
    Perform the compaction operation.  This reads in the bucket
    information from the database, builds a compacted bucket record,
    inserts that record in the appropriate place in the database, then
    removes outdated updates.

    :param db: A database handle for the Redis database.
    :param buck_key: A turnstile.limits.BucketKey instance containing
                     the bucket key.
    :param limit: The turnstile.limits.Limit object corresponding to
                  the bucket.
    """

    # Suck in the bucket records and generate our bucket
    records = db.lrange(str(buck_key), 0, -1)
    loader = limits.BucketLoader(limit.bucket_class, db, limit,
                                 str(buck_key), records, stop_summarize=True)

    # We now have the bucket loaded in; generate a 'bucket' record
    buck_record = msgpack.dumps(dict(bucket=loader.bucket.dehydrate(),
                                     uuid=str(uuid.uuid4())))

    # Now we need to insert it into the record list
    result = db.linsert(str(buck_key), 'after', loader.last_summarize_rec,
                        buck_record)

    # Were we successful?
    if result < 0:
        # Insert failed; we'll try again when max_age is hit
        LOG.warning("Bucket compaction on %s failed; will retry" % buck_key)
        return

    # OK, we have confirmed that the compacted bucket record has been
    # inserted correctly; now all we need to do is trim off the
    # outdated update records
    db.ltrim(str(buck_key), loader.last_summarize_idx + 1, -1)