Files
stoneheart_at_home/app/viewer_session.cpp
T

330 lines
13 KiB
C++

#include "viewer_session.hpp"
#include <chrono>
#include <limits>
#include <stdexcept>
#include <utility>
namespace settlement::viewer {
namespace {
template<class T>
bool ready(std::future<T>& completion) {
return completion.valid() && completion.wait_for(std::chrono::seconds{0}) == std::future_status::ready;
}
RulesManifest supported_rules() {
auto manifest = default_rules_manifest();
if (!manifest) throw std::runtime_error(manifest.error().message);
return std::move(*manifest);
}
void validate_supported(const WorldCheckpoint& candidate) {
const auto valid = validate_colony_checkpoint(candidate);
if (!valid) throw std::runtime_error(valid.error().message);
if (!candidate.world || candidate.world->width() != first_colony_map_size ||
candidate.world->height() != first_colony_map_size) {
throw std::runtime_error("This viewer opens worlds with a 32 by 32 map.");
}
}
WorldCheckpoint validated_initial(WorldCheckpoint candidate) {
validate_supported(candidate);
return candidate;
}
WorldCheckpoint initial_colony(std::size_t workers, ColonyProfile profile = ColonyProfile::Default) {
auto candidate = make_colony_checkpoint(profile, workers);
if (!candidate) throw std::runtime_error(candidate.error().message);
return std::move(*candidate);
}
RuntimeOptions suspended(RuntimeOptions options) {
options.ticking = false;
return options;
}
std::string exception_message() {
try { throw; }
catch (const std::exception& error) { return error.what(); }
catch (...) { return "The operation failed."; }
}
} // namespace
ViewerSession::ViewerSession(std::size_t workers, ViewerSessionOptions options)
: ViewerSession(initial_colony(workers), workers, std::move(options)) {}
ViewerSession::ViewerSession(WorldCheckpoint initial, std::size_t workers, ViewerSessionOptions options)
: workers_(workers), command_capacity_(options.command_capacity),
supported_rules_(supported_rules()),
runtime_(validated_initial(std::move(initial)), suspended(std::move(options.runtime))),
files_(std::move(options.files)) {
if (command_capacity_ == 0) throw std::invalid_argument("The command queue must have capacity.");
}
ViewerSession::~ViewerSession() = default;
std::shared_ptr<const World> ViewerSession::world() const {
return guest_ || (changing_world_ && guest_view_) ? guest_view_ : runtime_.latest()->world;
}
bool ViewerSession::can_submit() const {
return !guest_ && !changing_world_ && runtime_.view().state == RuntimeState::Running;
}
bool ViewerSession::can_host_legacy() const {
const auto current = runtime_.view();
return !guest_ && !changing_world_ && current.state == RuntimeState::Running &&
current.snapshot->rules && *current.snapshot->rules == supported_rules_;
}
std::optional<std::uint64_t> ViewerSession::submit(SessionPayload payload) {
if (!can_submit()) return std::nullopt;
for (const auto& intent : intents_) {
if (intent.payload == payload) return intent.id;
}
if (intents_.size() == command_capacity_ || next_intent_ == std::numeric_limits<std::uint64_t>::max()) {
return std::nullopt;
}
const auto id = next_intent_;
intents_.push_back({id, std::move(payload)});
++next_intent_;
return id;
}
bool ViewerSession::pending(std::uint64_t id) const noexcept {
for (const auto& intent : intents_) if (intent.id == id) return true;
return false;
}
LoadTicket ViewerSession::begin_change() {
if (generation_ == std::numeric_limits<std::uint64_t>::max()) {
throw std::overflow_error("The client operation counter is exhausted.");
}
auto ticket = runtime_.begin_load();
if (!ticket) throw std::runtime_error("The simulation cannot accept a world change.");
++generation_;
intents_.clear();
command_completion_ = {};
preparing_.reset();
installing_.reset();
install_completion_ = {};
events_.clear();
changing_world_ = true;
return *ticket;
}
void ViewerSession::validate_candidate(const WorldCheckpoint& candidate) const {
validate_supported(candidate);
}
void ViewerSession::replace(WorldCheckpoint candidate) {
validate_candidate(candidate);
const auto ticket = begin_change();
installing_.emplace(Installing{ticket, std::move(candidate)});
}
void ViewerSession::new_colony(ColonyProfile profile) {
replace(initial_colony(workers_, profile));
}
void ViewerSession::load(const std::filesystem::path& path) {
if (guest_) throw std::runtime_error("Only the host can load a world.");
const auto ticket = begin_change();
try {
auto operation = files_.try_load(path, workers_);
if (operation.admission != CheckpointLoadAdmission::Accepted) {
throw std::runtime_error("The file reader is busy or unavailable. Try again.");
}
preparing_.emplace(Preparing{ticket, std::move(operation.completion)});
} catch (...) {
changing_world_ = false;
throw;
}
}
void ViewerSession::save(const std::filesystem::path& path) {
if (guest_ || changing_world_) throw std::runtime_error("The current world cannot be saved yet.");
poll_saves();
const auto snapshot = runtime_.snapshot_for_save();
if (!snapshot) throw std::runtime_error("Load a valid world before saving after a simulation failure.");
// Reserve result tracking before accepting a write so allocation cannot lose
// the newest request's completion or its originating session.
saving_.reserve(saving_.size() + 1);
auto operation = files_.try_save(path, *snapshot);
if (operation.admission != SaveAdmission::Accepted) {
throw std::runtime_error("The save queue is busy or unavailable. Try again.");
}
latest_save_ = operation.request_id;
saving_.push_back({generation_, operation.request_id, (*snapshot)->identity.session,
std::move(operation.completion)});
}
void ViewerSession::enter_guest() {
static_cast<void>(begin_change());
guest_ = true;
changing_world_ = false;
guest_world_.reset();
guest_view_.reset();
}
void ViewerSession::receive_guest(std::unique_ptr<World> world) {
if (!guest_ || !world) return;
auto view = world->capture();
guest_world_ = std::move(world);
guest_view_ = std::move(view);
}
void ViewerSession::leave_guest() {
if (!guest_) return;
if (guest_world_) {
auto id = Void::Uuid::try_v4();
if (!id) throw std::runtime_error("Could not create a world identity.");
if (guest_world_->width() != first_colony_map_size || guest_world_->height() != first_colony_map_size) {
throw std::runtime_error("This viewer opens worlds with a 32 by 32 map.");
}
// All fallible preparation precedes moving the last received world.
auto rules = supported_rules_;
const auto ticket = begin_change();
installing_.emplace(Installing{ticket, {std::move(guest_world_), *id, 1, std::move(rules)}});
} else {
static_cast<void>(begin_change());
changing_world_ = false;
}
guest_ = false;
if (!changing_world_) guest_view_.reset();
}
void ViewerSession::fail_change(std::string message) {
preparing_.reset();
installing_.reset();
install_completion_ = {};
changing_world_ = false;
if (!guest_) guest_view_.reset();
events_.push_back({ViewerEventKind::Error, 0, {}, CommandStatus::Unavailable, std::move(message)});
}
void ViewerSession::poll_changes() {
if (preparing_ && ready(preparing_->completion)) {
const auto ticket = preparing_->ticket;
auto prepared = preparing_->completion.get();
preparing_.reset();
if (runtime_.latest()->identity.session != ticket.expected_session) {
fail_change("The load belongs to an earlier session.");
return;
}
if (!prepared) {
fail_change(prepared.error().message);
return;
}
validate_candidate(*prepared);
installing_.emplace(Installing{ticket, std::move(*prepared)});
}
if (installing_) {
auto result = runtime_.try_install(installing_->ticket, installing_->candidate);
if (result.admission == RuntimeAdmission::Accepted) {
install_completion_ = std::move(result.completion);
installing_.reset();
} else if (result.admission != RuntimeAdmission::Busy) {
fail_change("The simulation could not install this world.");
}
}
if (ready(install_completion_)) {
const auto result = install_completion_.get();
changing_world_ = false;
if (result.outcome == RuntimeOutcome::Completed && result.snapshot &&
result.snapshot->identity.session == runtime_.latest()->identity.session) {
guest_view_.reset();
fault_reported_ = false;
events_.push_back({ViewerEventKind::Replaced, 0, {}, CommandStatus::Unavailable, {}});
} else {
events_.push_back({ViewerEventKind::Error, 0, {}, CommandStatus::Unavailable,
"The world change failed or was superseded. The current view is retained."});
}
}
}
void ViewerSession::poll_commands() {
if (ready(command_completion_)) {
auto result = command_completion_.get();
if (!intents_.empty()) {
auto intent = std::move(intents_.front());
intents_.pop_front();
const auto status = result.outcome == RuntimeOutcome::Completed && result.receipt &&
result.receipt->status == DispatchStatus::Completed
? result.receipt->command_status : CommandStatus::Unavailable;
events_.push_back({ViewerEventKind::Command, intent.id, std::move(intent.payload), status, {}});
}
}
if (command_completion_.valid() || intents_.empty() || !can_submit()) return;
const auto current = runtime_.latest();
const CommandEnvelope command{command_envelope_version, current->identity.world, current->identity.session,
current->identity.city, current->next_requests[colony_host - 1], intents_.front().payload};
auto result = runtime_.try_submit({colony_host}, command);
if (result.admission == RuntimeAdmission::Accepted) {
command_completion_ = std::move(result.completion);
} else if (result.admission != RuntimeAdmission::Busy) {
auto intent = std::move(intents_.front());
intents_.pop_front();
events_.push_back({ViewerEventKind::Command, intent.id, std::move(intent.payload), CommandStatus::Unavailable, {}});
}
}
void ViewerSession::poll_saves() {
for (auto item = saving_.begin(); item != saving_.end();) {
if (!ready(item->completion)) {
++item;
continue;
}
const auto result = item->completion.get();
if (item->generation == generation_ && item->request == latest_save_ &&
item->session == runtime_.latest()->identity.session && !guest_) {
events_.push_back({result.succeeded() ? ViewerEventKind::Saved : ViewerEventKind::Error,
0, {}, CommandStatus::Unavailable,
result.succeeded() ? "" : result.visible_on_disk
? "The new save is visible, but its final disk status could not be confirmed."
: "The save failed. The previous slot remains available."});
}
item = saving_.erase(item);
}
}
void ViewerSession::poll_ticking() {
if (ready(ticking_completion_)) {
const auto result = ticking_completion_.get();
// The owner applies its ticking flag even while its world is faulted.
if (result.outcome == RuntimeOutcome::Completed || result.outcome == RuntimeOutcome::Faulted) {
applied_ticking_ = requested_ticking_;
}
}
const bool desired = desired_ticking_ && !guest_ && !changing_world_;
if (ticking_completion_.valid() || desired == applied_ticking_) return;
auto result = runtime_.set_ticking(desired);
if (result.admission == RuntimeAdmission::Accepted) {
requested_ticking_ = desired;
ticking_completion_ = std::move(result.completion);
}
}
std::vector<ViewerEvent> ViewerSession::poll() {
try {
poll_changes();
poll_commands();
poll_saves();
poll_ticking();
} catch (...) {
fail_change(exception_message());
}
if (!guest_ && runtime_.view().state == RuntimeState::Faulted && !fault_reported_) {
fault_reported_ = true;
intents_.clear();
command_completion_ = {};
events_.push_back({ViewerEventKind::Fault, 0, {}, CommandStatus::Unavailable,
"The simulation stopped at its last completed state. Load a save to continue."});
}
return std::exchange(events_, {});
}
} // namespace settlement::viewer