74 lines
2.8 KiB
C++
74 lines
2.8 KiB
C++
#include "google/sessions/engine_service.h"
|
|
|
|
#include "google/resource.h"
|
|
|
|
namespace molo::google::sessions {
|
|
|
|
using clients::body::Json;
|
|
|
|
EngineService::EngineService(std::shared_ptr<GoogleClient> client, EngineName engine,
|
|
Sleeper sleeper)
|
|
: Service(std::move(client), endpoints::aiplatform_beta(engine.location())),
|
|
engine_name_(std::move(engine)),
|
|
sleeper_(std::move(sleeper)) {}
|
|
|
|
Json EngineService::send(Call call, const std::string& resource, const Json* body,
|
|
const std::string& query) const {
|
|
const CallSpec& row = spec_of(call);
|
|
return client_->request(verb_of(row), endpoint_, expand(call, resource, query), body);
|
|
}
|
|
|
|
Operation EngineService::settle(const Json& reply) const {
|
|
Operation op = Operation::from_json(reply);
|
|
if (op.done) {
|
|
if (op.failed())
|
|
throw GoogleError(502, "OPERATION_FAILED", op.error_message, endpoint_.name);
|
|
return op;
|
|
}
|
|
if (op.name.empty())
|
|
throw GoogleError(502, "EMPTY_RESPONSE", "no operation returned", endpoint_.name);
|
|
return wait(op.name);
|
|
}
|
|
|
|
namespace {
|
|
void check_operation_name(const EngineName& engine, const std::string& name) {
|
|
const std::string prefix = engine.str() + "/";
|
|
bool ok = name.size() > prefix.size() && name.compare(0, prefix.size(), prefix) == 0 &&
|
|
name.find("/operations/") != std::string::npos &&
|
|
name.find("..") == std::string::npos && name.find('?') == std::string::npos &&
|
|
name.size() <= 512;
|
|
if (!ok) throw GoogleError::invalid("operation name must belong to this engine");
|
|
}
|
|
} // namespace
|
|
|
|
Json EngineService::operation(const std::string& operation_name) const {
|
|
check_operation_name(engine_name_, operation_name);
|
|
return send(Call::kOperationGet, operation_name);
|
|
}
|
|
|
|
void EngineService::cancel_operation(const std::string& operation_name) const {
|
|
check_operation_name(engine_name_, operation_name);
|
|
Json empty = Json::object();
|
|
send(Call::kOperationCancel, operation_name, &empty);
|
|
}
|
|
|
|
Operation EngineService::wait(const std::string& operation_name) const {
|
|
check_operation_name(engine_name_, operation_name);
|
|
return wait_operation(*client_, endpoint_, operation_name, sleeper_);
|
|
}
|
|
|
|
Json EngineService::list_items(Call call, const std::string& resource,
|
|
const std::string& query, const std::string& items_key,
|
|
std::size_t max_pages, std::size_t max_items) const {
|
|
Json items = list_all(*client_, endpoint_, expand(call, resource, query), items_key,
|
|
max_pages);
|
|
if (items.as_array().size() > max_items)
|
|
throw GoogleError(502, "RESULT_TOO_LARGE",
|
|
"more than " + std::to_string(max_items) +
|
|
" items; narrow the filter",
|
|
endpoint_.name);
|
|
return items;
|
|
}
|
|
|
|
} // namespace molo::google::sessions
|