/*
 * Copyright 2020 Bloomberg Finance LP
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <buildboxcasd_digestoperationqueue.h>

#include <buildboxcommon_logging.h>

void buildboxcasd::DigestOperationQueue::runExclusively(
    const buildboxcommon::Digest &digest, const DigestOperation &function)
{
    std::mutex &digestMutex = getDigestMutex(digest);
    digestMutex.lock();
    try {
        function(digest);
    }
    catch (const std::exception &e) {
        BUILDBOX_LOG_WARNING(
            "The given function threw an exception and it was ignored: "
            << e.what());
    }
    catch (...) {
        BUILDBOX_LOG_WARNING(
            "The given function threw an exception and it was ignored.");
    }

    // Function finished executing, updating the queue:
    std::lock_guard<std::mutex> queueLock(d_queueMutex);

    // Releasing the digest mutex, potentially waking up the next thread that
    // might be waiting on it:
    digestMutex.unlock();

    auto &digestEntry = d_queue.at(digest);
    if (digestEntry.second == 1) {
        // The last thread finished, we can delete the entry from the queue.
        d_queue.erase(digest);
    }
    else {
        digestEntry.second--; // Decrement reference counter.
    }
}

std::mutex &buildboxcasd::DigestOperationQueue::getDigestMutex(
    const buildboxcommon ::Digest &digest)
{
    const std::lock_guard<std::mutex> lock(d_queueMutex);
    // Exclusive access to the queue.

    auto it = d_queue.find(digest);
    if (it == d_queue.end()) {
        it = d_queue
                 .emplace(std::piecewise_construct, std::make_tuple(digest),
                          std::make_tuple())
                 .first;
        // (Using `piecewise_construct` because the pair value does not take
        // any arguments and thus can't be emplaced.)
    }

    it->second.second++; // Incrementing ref. counter
    return it->second.first;
}
