载入中...
搜索中...
未找到
ProductionAdvanced.cpp
浏览该文件的文档.
2
3#include <utility>
4
5#include <algorithm>
6#include <limits>
7
8namespace eve::production {
9namespace {
10
11template <class T>
12eve::Result<T> advancedFailure(eve::DiagnosticCode code, std::string message, std::string path = {}) {
14 eve::Diagnostic::error(code, std::move(message), std::move(path), {}, "production.advanced"));
15}
16
17eve::Result<std::int64_t> scaledRemaining(const ProductionTask& task) {
18 const auto remaining = task.duration.nanoseconds() - task.progress.nanoseconds();
19 const auto efficiency = static_cast<std::int64_t>(task.efficiencyPermille);
20 if (remaining <= 0) return eve::Result<std::int64_t>::success(0);
21 const auto whole = remaining / efficiency;
22 if (whole > std::numeric_limits<std::int64_t>::max() / 1000)
23 return advancedFailure<std::int64_t>(eve::DiagnosticCode::InvalidArgument,
24 "production remaining time is not representable");
25 const auto residualNumerator = (remaining % efficiency) * 1000 - task.workRemainderPermille;
26 const auto residual = residualNumerator <= 0 ? 0 : (residualNumerator + efficiency - 1) / efficiency;
27 const auto base = whole * 1000;
28 if (base > std::numeric_limits<std::int64_t>::max() - residual)
29 return advancedFailure<std::int64_t>(eve::DiagnosticCode::InvalidArgument,
30 "production remaining time is not representable");
31 return eve::Result<std::int64_t>::success(base + residual);
32}
33
34} // namespace
35
37 const auto it = std::lower_bound(schedulerStrategies_.begin(), schedulerStrategies_.end(), owner,
38 [](const auto& entry, std::string_view key) { return entry.first < key; });
39 return it != schedulerStrategies_.end() && it->first == owner ? it->second : SchedulerStrategy::Priority;
40}
41
43 std::string_view owner, const eve::definition::DefinitionHandle& definition) const {
44 const auto key = std::tuple(std::string(owner), definition.reference.id().format(), definition.generation.value());
45 return std::binary_search(availableDefinitions_.begin(), availableDefinitions_.end(), key);
46}
47
48bool WorkQueue::tagAvailable(std::string_view owner, std::string_view tag) const {
49 return std::binary_search(availableTags_.begin(), availableTags_.end(),
50 std::pair(std::string(owner), std::string(tag)));
51}
52
54 std::string_view owner, const eve::definition::DefinitionHandle& definition, bool available) {
55 if (owner.empty() || !definition.isValid())
56 return advancedFailure<void>(eve::DiagnosticCode::InvalidArgument,
57 "definition availability needs an owner and valid handle");
58 const auto key = std::tuple(std::string(owner), definition.reference.id().format(), definition.generation.value());
59 auto it = std::lower_bound(availableDefinitions_.begin(), availableDefinitions_.end(), key);
60 const bool exists = it != availableDefinitions_.end() && *it == key;
61 if (available && !exists) availableDefinitions_.insert(it, key);
62 if (!available && exists) availableDefinitions_.erase(it);
66}
67
68eve::Result<void> WorkQueue::setTagAvailable(std::string_view owner, std::string_view tag, bool available) {
69 if (owner.empty() || tag.empty())
70 return advancedFailure<void>(eve::DiagnosticCode::InvalidArgument,
71 "tag availability needs an owner and tag");
72 const auto key = std::pair(std::string(owner), std::string(tag));
73 auto it = std::lower_bound(availableTags_.begin(), availableTags_.end(), key);
74 const bool exists = it != availableTags_.end() && *it == key;
75 if (available && !exists) availableTags_.insert(it, key);
76 if (!available && exists) availableTags_.erase(it);
80}
81
83 if (owner.empty())
84 return advancedFailure<void>(eve::DiagnosticCode::InvalidArgument, "scheduler owner is required", "owner");
85 auto it = std::lower_bound(schedulerStrategies_.begin(), schedulerStrategies_.end(), owner,
86 [](const auto& entry, std::string_view key) { return entry.first < key; });
87 if (it != schedulerStrategies_.end() && it->first == owner)
88 it->second = strategy;
89 else
90 schedulerStrategies_.insert(it, {std::string(owner), strategy});
93}
94
95void WorkQueue::continueAfterCycle(ProductionTask& task) {
96 ++task.completedCycles;
97 const bool repeats = task.repeat.continuous || task.completedCycles < task.repeat.totalCycles;
98 if (!repeats) return;
99 if (task.repeat.maintainStockTarget >= 0) {
100 const auto updated = static_cast<std::int64_t>(task.repeat.observedStock) + task.batchSize;
101 task.repeat.observedStock = static_cast<int>(std::min<std::int64_t>(updated, std::numeric_limits<int>::max()));
102 }
104 task.workRemainderPermille = 0;
105 task.reason.clear();
107 task.settlement = {};
111}
112
114 std::string_view taskId, std::string_view releaseId) {
115 auto* task = mutableFind(taskId);
116 if (task == nullptr)
117 return advancedFailure<ProductionReservationRelease>(eve::DiagnosticCode::NotFound,
118 "work task was not found", "taskId");
119 if (releaseId.empty())
120 return advancedFailure<ProductionReservationRelease>(eve::DiagnosticCode::InvalidArgument,
121 "reservation release id is required", "releaseId");
123 task->reservationRelease.releaseId == releaseId)
126 if (task->state != TaskState::Cancelled && task->state != TaskState::Failed)
127 return advancedFailure<ProductionReservationRelease>(eve::DiagnosticCode::Conflict,
128 "only cancelled or failed tasks can release reservations",
129 "taskId");
131 return advancedFailure<ProductionReservationRelease>(eve::DiagnosticCode::Conflict,
132 "task has no releasable reservation", "taskId");
133 task->reservationRelease = {std::string(releaseId), task->reservation, task->refundPermille};
137}
138
139eve::Result<void> WorkQueue::reportStock(std::string_view taskId, int observedStock) {
140 auto* task = mutableFind(taskId);
141 if (task == nullptr)
142 return advancedFailure<void>(eve::DiagnosticCode::NotFound, "work task was not found", "taskId");
143 if (task->repeat.maintainStockTarget < 0 || observedStock < 0)
144 return advancedFailure<void>(eve::DiagnosticCode::InvalidArgument,
145 "task has no maintain-stock policy or stock is negative", "observedStock");
146 task->repeat.observedStock = observedStock;
147 schedule(task->owner);
149}
150
152 std::uint32_t maxSteps) {
153 if (target < tick_ || fixedDelta.nanoseconds() <= 0 || maxSteps == 0)
154 return advancedFailure<std::uint32_t>(eve::DiagnosticCode::InvalidArgument,
155 "advanceTo needs a future target, positive delta and step budget");
156 const auto distance = target.value() - tick_.value();
157 if (distance > maxSteps)
158 return advancedFailure<std::uint32_t>(eve::DiagnosticCode::PreconditionViolation,
159 "advanceTo step budget is insufficient", "maxSteps");
160 std::uint32_t applied = 0;
161 while (tick_ < target) {
162 auto step = advance({eve::SimulationTick(tick_.value() + 1), fixedDelta});
163 if (!step) return eve::Result<std::uint32_t>::failure(step.status());
164 ++applied;
165 }
167}
168
170 const auto reference = find(taskId);
171 if (!reference)
172 return advancedFailure<ProductionPrediction>(eve::DiagnosticCode::NotFound,
173 "work task was not found", "taskId");
174 const auto& task = reference->get();
175 ProductionPrediction prediction;
176 auto reason = blockReason(taskId);
177 if (!reason) return eve::Result<ProductionPrediction>::failure(reason.status());
178 prediction.blockReason = reason.value();
179 auto own = scaledRemaining(task);
180 if (!own) return eve::Result<ProductionPrediction>::failure(own.status());
181 prediction.ownWorkRemaining = eve::Duration::fromNanoseconds(own.value());
182 if (task.state == TaskState::Running) {
183 prediction.estimatedCompletionAfter = prediction.ownWorkRemaining;
184 prediction.exact = true;
185 return eve::Result<ProductionPrediction>::success(std::move(prediction));
186 }
187 std::int64_t earliest = 0;
188 if (runningCount(task.owner) >= slotCount(task.owner)) {
189 earliest = std::numeric_limits<std::int64_t>::max();
190 for (const auto& candidate : tasks_)
191 if (candidate->owner == task.owner && candidate->state == TaskState::Running)
192 {
193 auto candidateRemaining = scaledRemaining(*candidate);
194 if (!candidateRemaining)
195 return eve::Result<ProductionPrediction>::failure(candidateRemaining.status());
196 earliest = std::min(earliest, candidateRemaining.value());
197 }
198 if (earliest == std::numeric_limits<std::int64_t>::max()) earliest = 0;
199 }
201 if (earliest > std::numeric_limits<std::int64_t>::max() - own.value())
202 return advancedFailure<ProductionPrediction>(eve::DiagnosticCode::InvalidArgument,
203 "production completion estimate is not representable");
204 prediction.estimatedCompletionAfter = eve::Duration::fromNanoseconds(earliest + own.value());
205 prediction.exact = prediction.blockReason.empty() && task.state == TaskState::Queued && earliest == 0;
206 return eve::Result<ProductionPrediction>::success(std::move(prediction));
207}
208
210 const auto reference = find(taskId);
211 if (!reference)
212 return advancedFailure<ProductionDiagnostic>(eve::DiagnosticCode::NotFound,
213 "work task was not found", "taskId");
214 const auto& task = reference->get();
215 auto reason = blockReason(taskId);
216 if (!reason) return eve::Result<ProductionDiagnostic>::failure(reason.status());
217 ProductionDiagnostic diagnostic;
218 diagnostic.correlationId = task.correlationId;
219 diagnostic.taskId = task.id;
220 diagnostic.tick = tick_;
221 diagnostic.code = reason.value().empty() ? std::string(taskStateName(task.state)) : reason.value();
222 diagnostic.message = reason.value().empty() ? "task state is " + std::string(taskStateName(task.state))
223 : "task is blocked: " + reason.value();
224 return eve::Result<ProductionDiagnostic>::success(std::move(diagnostic));
225}
226
227} // namespace eve::production
LogicalId target
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
bool applied
SQObjectPtr key
Definition ECS.cpp:155
float efficiency
std::string message
DiagnosticCode code
bool exists
float distance
const std::string * tag
std::shared_ptr< OceanGpuSpectrum > owner
std::array< std::uint64_t, kPixelChunkSize *kPixelChunkSize > updated
std::string path
Definition PlayHost.cpp:111
std::string taskId
std::vector< ecs::EntityHandle > schedule
The round's activation queue, resolved against the target battle.
float step
Definition TreeMesh.cpp:451
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Signed, fixed-resolution simulation duration in nanoseconds.
Definition Time.h:43
constexpr std::int64_t nanoseconds() const noexcept
Return the exact signed nanosecond representation.
Definition Time.h:69
static constexpr Duration fromNanoseconds(std::int64_t nanoseconds) noexcept
Construct an exact duration from nanoseconds.
Definition Time.h:55
static constexpr Duration zero() noexcept
Return zero duration.
Definition Time.h:60
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
eve::Result< std::string > blockReason(std::string_view taskId) const
Returns the deterministic reason a task cannot start, or an empty string when runnable.
bool definitionAvailable(std::string_view owner, const eve::definition::DefinitionHandle &definition) const
Reports whether an exact definition incarnation is available to an owner.
bool tagAvailable(std::string_view owner, std::string_view tag) const
Reports whether an exact tag is available to an owner.
eve::OptionalRef< const ProductionTask > find(std::string_view taskId)
Finds a retained task by stable ID.
eve::Result< std::uint32_t > advanceTo(eve::SimulationTick target, eve::Duration fixedDelta, std::uint32_t maxSteps)
Advances through bounded fixed steps to a target tick.
eve::Result< void > setSchedulerStrategy(std::string_view owner, SchedulerStrategy strategy)
Selects an owner's deterministic queue ordering strategy.
eve::Result< void > setDefinitionAvailable(std::string_view owner, const eve::definition::DefinitionHandle &definition, bool available)
Publishes or withdraws one generation-qualified definition fact for an owner.
eve::Result< ProductionPrediction > predict(std::string_view taskId) const
Predicts task timing without mutating queue state.
SchedulerStrategy schedulerStrategy(std::string_view owner) const
Returns an owner's queue ordering strategy, defaulting to Priority.
eve::Result< void > setTagAvailable(std::string_view owner, std::string_view tag, bool available)
Publishes or withdraws one exact tag fact for an owner.
eve::Result< ProductionReservationRelease > releaseReservation(std::string_view taskId, std::string_view releaseId)
Idempotently releases cancelled/failed reservation evidence for domain rollback.
eve::Result< void > reportStock(std::string_view taskId, int observedStock)
Reports current domain stock for a maintain-stock task and reschedules deterministically.
int runningCount(std::string_view owner) const
Returns the number of currently running tasks for an owner.
eve::Result< ProductionDiagnostic > diagnose(std::string_view taskId) const
Returns structured diagnostic state for a task.
eve::Result< void > advance(const eve::SimulationStep &step)
Applies one injected deterministic simulation step.
int slotCount(std::string_view owner) const
Returns an owner's slot count, defaulting to one.
SchedulerStrategy
Stable owner-local queue ordering strategy.
Definition Production.h:87
std::string_view taskStateName(TaskState state)
Returns the stable lowercase name of a task state.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
A generation-qualified reference to one definition incarnation.
Structured task diagnostic carrying stable correlation identity.
Definition Production.h:115
Side-effect-free estimate under an unchanged queue configuration.
Definition Production.h:106
A subject-agnostic continuous task retained for audit and save games.
Definition Production.h:158
ReservationState reservationState
Definition Production.h:169
ProductionRepeatPolicy repeat
Definition Production.h:177
std::uint32_t workRemainderPermille
Unapplied fixed-point work numerator in thousandths of one nanosecond.
Definition Production.h:183
ProductionSettlementReceipt settlement
Definition Production.h:171
ProductionReservationRelease reservationRelease
Definition Production.h:170