Files
stoneheart_at_home/engine/src/simulation_runtime.cpp
T

373 lines
15 KiB
C++

#include "settlement/core/simulation_runtime.hpp"
#include <Void/Async/FuturePool.hpp>
#include <Void/Async/ThreadExecutor.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <limits>
#include <mutex>
#include <stdexcept>
#include <utility>
namespace settlement {
namespace {
using Clock = Void::Time::MonotonicClock;
constexpr auto tick_interval = std::chrono::milliseconds(50);
SessionIdentity new_identity(const WorldCheckpoint& checkpoint) {
if (!checkpoint.world || checkpoint.world_id.is_nil() || checkpoint.city == 0) {
throw std::invalid_argument("runtime requires a world, nonnil identity and a city");
}
const auto session = Void::Uuid::try_v4();
if (!session) throw std::runtime_error("cannot generate a simulation session UUID");
return {checkpoint.world_id, *session, checkpoint.city};
}
std::shared_ptr<const PublishedSnapshot> capture(
const World& world, const CommandDispatcher& dispatcher,
std::shared_ptr<const RulesManifest> rules, std::uint64_t revision) {
std::array<std::uint64_t, colony_player_slots> next{};
for (std::size_t i = 0; i < next.size(); ++i) {
next[i] = dispatcher.next_request({static_cast<std::uint8_t>(i + colony_host)});
}
return std::make_shared<const PublishedSnapshot>(
dispatcher.identity(), revision, world.capture(), std::move(rules), next);
}
} // namespace
struct SimulationRuntime::Impl {
enum class Kind { Command, Ticking, Fence, Install };
struct Work {
Kind kind;
TrustedClient client{};
CommandEnvelope command{};
bool enabled = false;
Clock::time_point deadline{};
LoadTicket ticket{};
std::optional<WorldCheckpoint> candidate;
std::promise<RuntimeResult> promise;
explicit Work(Kind value) : kind(value) {}
};
RuntimeOptions options;
std::shared_ptr<const Clock> clock;
std::unique_ptr<World> world;
mutable std::mutex mutex;
std::condition_variable changed;
std::deque<std::unique_ptr<Work>> queue;
std::size_t outstanding = 0;
std::uint64_t latest_load = 0;
RuntimeState state = RuntimeState::Running;
std::exception_ptr failure;
std::shared_ptr<const PublishedSnapshot> published;
std::shared_ptr<const CommandDispatcher> committed;
std::atomic<bool> stopping{false};
bool owner_faulted = false;
bool ticking;
Clock::time_point next_tick;
std::unique_ptr<Void::Async::ThreadExecutor> executor;
std::unique_ptr<Void::Async::FuturePool> futures;
std::future<void> owner_done;
Impl(WorldCheckpoint initial, RuntimeOptions settings)
: options(std::move(settings)),
clock(options.clock ? options.clock : std::make_shared<Void::Time::SystemMonotonicClock>()),
ticking(options.ticking) {
if (options.capacity == 0) throw std::invalid_argument("runtime capacity must be positive");
auto dispatcher = std::make_shared<CommandDispatcher>(new_identity(initial), options.dispatcher);
auto rules = std::make_shared<const RulesManifest>(std::move(initial.rules));
published = capture(*initial.world, *dispatcher, std::move(rules), 0);
committed = std::move(dispatcher);
world = std::move(initial.world);
reanchor();
auto created = Void::Async::ThreadExecutor::create({.workers = 1, .max_admitted = 1});
if (!created) throw std::runtime_error(created.error().message());
executor = std::move(*created);
futures = std::make_unique<Void::Async::FuturePool>(*executor);
const auto started = executor->start();
if (!started) throw std::runtime_error(started.error().message());
auto submitted = futures->try_submit([this] { run(); });
if (!submitted) throw std::runtime_error("cannot start simulation owner");
owner_done = std::move(*submitted);
}
~Impl() { shutdown(); }
void reanchor() { next_tick = Void::Time::saturating_add(clock->now(), tick_interval); }
bool advancing() const { return !owner_faulted && ticking && world && !world->paused(); }
void observe(RuntimePhase phase) const { if (options.observer) options.observer(phase); }
std::uint64_t next_revision() const {
if (published->revision == std::numeric_limits<std::uint64_t>::max()) {
throw std::overflow_error("publication revision exhausted");
}
return published->revision + 1;
}
RuntimeSubmission enqueue(std::unique_ptr<Work> work, WorldCheckpoint* candidate = nullptr) {
auto completion = work->promise.get_future();
std::unique_lock lock(mutex, std::try_to_lock);
if (!lock.owns_lock()) return {RuntimeAdmission::Busy, {}};
if (stopping.load()) return {RuntimeAdmission::Closed, {}};
if (outstanding == options.capacity) return {RuntimeAdmission::Busy, {}};
queue.push_back(std::move(work));
if (candidate) {
static_assert(std::is_nothrow_move_constructible_v<WorldCheckpoint>);
queue.back()->candidate.emplace(std::move(*candidate));
}
++outstanding;
lock.unlock();
changed.notify_one();
return {RuntimeAdmission::Accepted, std::move(completion)};
}
bool publish(std::shared_ptr<const PublishedSnapshot> snapshot,
std::shared_ptr<const CommandDispatcher> ledger) {
{
std::lock_guard lock(mutex);
if (stopping.load()) return false;
published.swap(snapshot);
committed.swap(ledger);
}
return true;
}
void fault() {
owner_faulted = true;
const auto error = std::current_exception();
{
std::lock_guard lock(mutex);
if (!stopping.load()) {
state = RuntimeState::Faulted;
failure = error;
}
}
// All World stage tasks have drained before an exception reaches here.
world.reset();
}
void tick() {
try {
const auto following = Void::Time::saturating_add(next_tick, tick_interval);
if (following == next_tick) throw std::overflow_error("simulation clock exhausted");
observe(RuntimePhase::BeforeTick);
world->step();
observe(RuntimePhase::BeforeCapture);
auto snapshot = capture(*world, *committed, published->rules, next_revision());
static_cast<void>(publish(std::move(snapshot), committed));
next_tick = following;
} catch (...) {
fault();
}
}
RuntimeResult command(Work& work) {
if (const auto receipt = committed->lookup(work.client, work.command)) {
return {RuntimeOutcome::Completed, *receipt, published};
}
if (owner_faulted) return {RuntimeOutcome::Faulted, {}, published};
try {
const bool was_paused = world->paused();
auto candidate = std::make_shared<CommandDispatcher>(*committed);
const auto receipt = candidate->dispatch(*world, work.client, work.command);
if (receipt.status != DispatchStatus::Completed) {
return {RuntimeOutcome::Completed, receipt, published};
}
observe(RuntimePhase::BeforeCapture);
auto snapshot = capture(*world, *candidate, published->rules, next_revision());
if (!publish(std::move(snapshot), std::move(candidate))) {
return {RuntimeOutcome::Closed, {}, published};
}
if (was_paused != world->paused()) reanchor();
return {RuntimeOutcome::Completed, receipt, published};
} catch (...) {
fault();
return {RuntimeOutcome::Faulted, {}, published};
}
}
bool current_ticket(const LoadTicket& ticket) const {
return ticket.request != 0 && ticket.request == latest_load &&
ticket.expected_session == published->identity.session;
}
RuntimeResult install(Work& work) {
{
std::lock_guard lock(mutex);
if (!current_ticket(work.ticket)) return {RuntimeOutcome::Superseded, {}, published};
}
try {
auto& candidate = *work.candidate;
auto ledger = std::make_shared<CommandDispatcher>(new_identity(candidate), options.dispatcher);
auto rules = std::make_shared<const RulesManifest>(std::move(candidate.rules));
observe(RuntimePhase::BeforeInstallCapture);
auto snapshot = capture(*candidate.world, *ledger, std::move(rules), next_revision());
std::shared_ptr<const CommandDispatcher> immutable_ledger = std::move(ledger);
{
std::lock_guard lock(mutex);
if (stopping.load()) return {RuntimeOutcome::Closed, {}, published};
if (!current_ticket(work.ticket)) return {RuntimeOutcome::Superseded, {}, published};
world.swap(candidate.world);
published.swap(snapshot);
committed.swap(immutable_ledger);
owner_faulted = false;
state = RuntimeState::Running;
failure = {};
}
reanchor();
return {RuntimeOutcome::Completed, {}, published};
} catch (...) {
return {RuntimeOutcome::InvalidCandidate, {}, published};
}
}
RuntimeResult process(Work& work) {
if (stopping.load()) return {RuntimeOutcome::Closed, {}, published};
switch (work.kind) {
case Kind::Command: return command(work);
case Kind::Install: return install(work);
case Kind::Ticking:
if (ticking != work.enabled) {
ticking = work.enabled;
reanchor();
}
break;
case Kind::Fence: break;
}
return {owner_faulted ? RuntimeOutcome::Faulted : RuntimeOutcome::Completed, {}, published};
}
void run() {
for (;;) {
std::unique_ptr<Work> work;
bool due = false;
{
std::unique_lock lock(mutex);
// No domain work or snapshot destruction occurs while holding mutex.
for (;;) {
if (stopping.load() && queue.empty()) return;
due = !stopping.load() && advancing() && next_tick <= clock->now();
if (!queue.empty()) {
const auto& front = *queue.front();
if (!(due && front.kind == Kind::Fence && next_tick <= front.deadline)) {
work = std::move(queue.front());
queue.pop_front();
}
break;
}
if (due) break;
if (advancing()) {
changed.wait_for(lock, Void::Time::remaining_until(*clock, next_tick));
} else {
changed.wait(lock);
}
}
}
if (work) {
auto result = process(*work);
{
std::lock_guard lock(mutex);
--outstanding;
}
work->promise.set_value(std::move(result));
work.reset();
// One tick per turn bounds catch-up work and lets queued input run.
if (!stopping.load() && advancing() && next_tick <= clock->now()) tick();
} else if (due) {
tick();
}
}
}
void shutdown() {
if (executor && executor->is_executor_thread()) {
throw std::logic_error("cannot shut down runtime from its owner");
}
{
std::lock_guard lock(mutex);
stopping.store(true);
state = RuntimeState::Closed;
}
changed.notify_all();
if (executor) static_cast<void>(executor->join());
}
};
SimulationRuntime::SimulationRuntime(WorldCheckpoint initial, RuntimeOptions options)
: impl_(std::make_unique<Impl>(std::move(initial), std::move(options))) {}
SimulationRuntime::~SimulationRuntime() = default;
std::shared_ptr<const PublishedSnapshot> SimulationRuntime::latest() const {
std::lock_guard lock(impl_->mutex);
return impl_->published;
}
RuntimeView SimulationRuntime::view() const {
std::lock_guard lock(impl_->mutex);
return {impl_->state, impl_->published, impl_->failure};
}
std::expected<std::shared_ptr<const PublishedSnapshot>, RuntimeState> SimulationRuntime::snapshot_for_save() const {
std::lock_guard lock(impl_->mutex);
if (impl_->state != RuntimeState::Running) return std::unexpected{impl_->state};
return impl_->published;
}
std::optional<DispatchReceipt> SimulationRuntime::lookup(
TrustedClient client, const CommandEnvelope& command) const {
std::shared_ptr<const CommandDispatcher> ledger;
{
std::lock_guard lock(impl_->mutex);
ledger = impl_->committed;
}
return ledger->lookup(client, command);
}
RuntimeSubmission SimulationRuntime::try_submit(TrustedClient client, const CommandEnvelope& command) {
auto work = std::make_unique<Impl::Work>(Impl::Kind::Command);
work->client = client;
work->command = command;
return impl_->enqueue(std::move(work));
}
RuntimeSubmission SimulationRuntime::set_ticking(bool enabled) {
auto work = std::make_unique<Impl::Work>(Impl::Kind::Ticking);
work->enabled = enabled;
return impl_->enqueue(std::move(work));
}
RuntimeSubmission SimulationRuntime::synchronize() {
auto work = std::make_unique<Impl::Work>(Impl::Kind::Fence);
work->deadline = impl_->clock->now();
return impl_->enqueue(std::move(work));
}
void SimulationRuntime::notify_clock() {
// Pair with the owner's wait lock so a notification cannot be lost between
// checking the injected clock and beginning the condition-variable wait.
{ std::lock_guard lock(impl_->mutex); }
impl_->changed.notify_one();
}
std::expected<LoadTicket, RuntimeAdmission> SimulationRuntime::begin_load() {
std::lock_guard lock(impl_->mutex);
if (impl_->stopping.load()) return std::unexpected{RuntimeAdmission::Closed};
if (impl_->latest_load == std::numeric_limits<std::uint64_t>::max()) {
return std::unexpected{RuntimeAdmission::IdExhausted};
}
return LoadTicket{++impl_->latest_load, impl_->published->identity.session};
}
RuntimeSubmission SimulationRuntime::try_install(LoadTicket ticket, WorldCheckpoint& candidate) {
auto work = std::make_unique<Impl::Work>(Impl::Kind::Install);
work->ticket = ticket;
return impl_->enqueue(std::move(work), &candidate);
}
void SimulationRuntime::shutdown() { impl_->shutdown(); }
} // namespace settlement