/*
 * 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.
 */

#ifndef INCLUDED_BUILDBOXWORKER_ACTIONUTILS
#define INCLUDED_BUILDBOXWORKER_ACTIONUTILS

#include <buildboxworker_worker.h>

#include <buildboxcommon_protos.h>
#include <buildboxcommon_temporaryfile.h>

#include <google/devtools/remoteworkers/v1test2/bots.grpc.pb.h>

namespace buildboxworker {

namespace proto {
using namespace google::devtools::remoteworkers::v1test2;
} // namespace proto

struct ActionUtils {
    // Needed for testing
    virtual ~ActionUtils();

    /*
     * Given a `Lease`, return a tuple with the `Action` that it contains and
     * its digest.
     *
     * The payload of the lease can be an `Action` or a `Digest` message.
     *
     * If the payload is an `Action`, it's unpacked and returned directly.
     *
     * If the payload is a `Digest`, use the given `connectionOptions` to fetch
     * the corresponding `Action` from that CAS server.
     *
     * If the payload contains any other type, or there are parsing or fetching
     * errors, throws `std::runtime_error`.
     *
     *
     * [Metrics]: updates the `TIMER_NAME_DOWNLOAD_ACTION` with this function's
     * running time.
     *
     */
    static std::pair<buildboxcommon::Action, buildboxcommon::Digest>
    getActionFromLease(
        const proto::Lease &lease,
        const std::shared_ptr<buildboxcommon::CASClient> &casClient);

    /*
     * Given a the digest of an action and a shared_ptr to a CASClient,
     * download the `Action` message from it.
     */
    static buildboxcommon::Action downloadAction(
        const buildboxcommon::Digest &digest,
        const std::shared_ptr<buildboxcommon::CASClient> &casClient);
};

} // namespace buildboxworker

#endif
