Files
WoW-Hybrid-gateway/native/inspect_request_history.hpp
2026-11-23 03:28:32 +02:00

68 lines
2.5 KiB
C++

#pragma once
#include <chrono>
#include <cstdint>
#include <limits>
#include <map>
#include <optional>
#include <stdexcept>
// The realm answers only approved inspections and echoes only the character
// GUID. A missing answer can never be distinguished from a delayed answer.
template<class Peer>
struct InspectRequestHistory {
using Clock = std::chrono::steady_clock;
static constexpr auto lifetime = std::chrono::seconds(5);
struct Pending {
Peer peer;
uint64_t epoch, count;
Clock::time_point sent;
};
std::optional<Pending> pending;
// A counter per unresolved GUID, independent of the active selection.
// Keep just enough information to discard late untagged replies. Counts
// belong to one authenticated world session and hold no equipment data.
std::map<uint64_t, uint64_t> retired;
void retire() {
if (!pending) return;
auto& debt = retired[pending->peer.guid];
debt += pending->count; // can_send bounds the total for this GUID.
pending.reset();
}
void expire(Clock::time_point now) {
if (pending && now - pending->sent >= lifetime) retire();
}
bool waiting(const Peer& peer, uint64_t epoch, Clock::time_point now) const {
return pending && pending->peer == peer && pending->epoch == epoch &&
now - pending->sent < lifetime;
}
bool can_send(uint64_t guid) const {
const auto found = retired.find(guid);
const auto older = found == retired.end() ? 0 : found->second;
const auto current = pending && pending->peer.guid == guid ? pending->count : 0;
return std::numeric_limits<uint64_t>::max() - older > current;
}
void sent(const Peer& peer, uint64_t epoch, Clock::time_point now) {
if (!can_send(peer.guid)) throw std::overflow_error("Inspect reply count exhausted");
if (waiting(peer, epoch, now)) {
++pending->count;
return;
}
retire();
pending = Pending{peer, epoch, 1, now};
}
std::optional<Pending> consume(uint64_t guid, Clock::time_point now) {
expire(now);
auto previous = retired.find(guid);
if (previous != retired.end()) {
if (--previous->second == 0) retired.erase(previous);
return {};
}
if (!pending || pending->peer.guid != guid) return {};
auto accepted = *pending;
if (--pending->count == 0) pending.reset();
return accepted;
}
};