载入中...
搜索中...
未找到
EditingTaskService.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <exception>
5
6namespace eve::editing {
7
9 TaskSnapshot snapshot;
10 Work work;
11 bool discarded = false;
12 std::shared_ptr<std::atomic_bool> cancelled = std::make_shared<std::atomic_bool>(false);
13};
14
15TaskContext::TaskContext(std::shared_ptr<std::atomic_bool> cancelled, std::function<void(float)> progress)
16 : cancelled_(std::move(cancelled)), progress_(std::move(progress)) {}
17
19 return cancelled_ && cancelled_->load(std::memory_order_relaxed);
20}
21
22void TaskContext::reportProgress(float progress) const {
23 if (progress_) progress_(std::clamp(progress, 0.0F, 1.0F));
24}
25
27 // Start only after all members, including stopping_, have been initialized.
28 worker_ = std::thread([this] { workerLoop(); });
29}
30
32 {
33 std::lock_guard lock(mutex_);
34 stopping_ = true;
35 for (auto& [id, task] : tasks_) {
36 (void)id;
37 task->cancelled->store(true, std::memory_order_relaxed);
38 }
39 }
40 workReady_.notify_all();
41 if (worker_.joinable()) worker_.join();
42}
43
45 if (name.empty() || !work)
46 return eve::editing::failed<TaskId>(Status::Rejected, RuleId("editing.task.invalid"),
47 "Task name and worker are required");
48 auto task = std::make_shared<TaskRecord>();
49 task->snapshot.name = std::move(name);
50 task->work = std::move(work);
51 TaskId id;
52 {
53 std::lock_guard lock(mutex_);
54 if (stopping_)
55 return eve::editing::failed<TaskId>(Status::Rejected, RuleId("editing.task.stopping"),
56 "Task service is stopping");
57 task->snapshot.id = TaskId("editor.task." + std::to_string(++sequence_));
58 id = task->snapshot.id;
59 tasks_.emplace(id, task);
60 queue_.push_back(std::move(task));
61 }
62 workReady_.notify_one();
63 return eve::editing::applied<TaskId>(id);
64}
65
67 std::lock_guard lock(mutex_);
68 auto found = tasks_.find(task);
69 if (found == tasks_.end())
70 return eve::editing::failed<void>(Status::NotFound, RuleId("editing.task.not-found"),
71 "Task does not exist");
72 auto& record = *found->second;
73 if (record.snapshot.state == TaskState::Succeeded || record.snapshot.state == TaskState::Failed ||
74 record.snapshot.state == TaskState::Cancelled)
75 return eve::editing::failed<void>(Status::Conflict, RuleId("editing.task.already-finished"),
76 "Finished tasks cannot be cancelled");
77 record.cancelled->store(true, std::memory_order_relaxed);
78 if (record.snapshot.state == TaskState::Queued) record.snapshot.state = TaskState::Cancelled;
79 workReady_.notify_all();
80 return eve::editing::applied<void>();
81}
82
84 std::shared_ptr<TaskRecord> released;
85 {
86 std::lock_guard lock(mutex_);
87 auto found = tasks_.find(id);
88 if (found == tasks_.end())
89 return editing::failed<void>(Status::NotFound, RuleId("editing.task.not-found"), "Task does not exist");
90 auto& record = *found->second;
91 record.cancelled->store(true, std::memory_order_relaxed);
92 record.discarded = true;
93 if (record.snapshot.state != TaskState::Running) {
94 released = found->second;
95 std::erase(queue_, released);
96 tasks_.erase(found);
97 }
98 }
99 // Captures can own arbitrary provider destructors; release them outside the mutex.
100 released.reset();
101 idle_.notify_all();
102 return editing::applied<void>();
103}
104
106 std::lock_guard lock(mutex_);
107 auto found = tasks_.find(task);
108 if (found == tasks_.end())
109 return eve::editing::failed<TaskSnapshot>(Status::NotFound, RuleId("editing.task.not-found"),
110 "Task does not exist");
111 return eve::editing::applied<TaskSnapshot>(found->second->snapshot);
112}
113
114Result<void> TaskService::waitIdle(std::chrono::milliseconds timeout) {
115 std::unique_lock lock(mutex_);
116 const bool idle = idle_.wait_for(lock, timeout, [this] {
117 if (!queue_.empty()) return false;
118 return std::none_of(tasks_.begin(), tasks_.end(),
119 [](const auto& entry) { return entry.second->snapshot.state == TaskState::Running; });
120 });
121 if (!idle)
122 return eve::editing::failed<void>(Status::Failed, eve::DiagnosticCode::Failed,
123 RuleId("editing.task.wait-timeout"),
124 "Task service did not become idle before the deadline");
125 return eve::editing::applied<void>();
126}
127
128void TaskService::workerLoop() {
129 while (true) {
130 std::shared_ptr<TaskRecord> task;
131 {
132 std::unique_lock lock(mutex_);
133 workReady_.wait(lock, [this] { return stopping_ || !queue_.empty(); });
134 if (stopping_ && queue_.empty()) return;
135 task = queue_.front();
136 queue_.pop_front();
137 if (task->cancelled->load(std::memory_order_relaxed)) {
138 task->snapshot.state = TaskState::Cancelled;
139 idle_.notify_all();
140 continue;
141 }
142 task->snapshot.state = TaskState::Running;
143 }
144
145 TaskOutcome outcome;
146 try {
147 TaskContext context(task->cancelled, [this, weak = std::weak_ptr<TaskRecord>(task)](float value) {
148 if (auto record = weak.lock()) {
149 std::lock_guard lock(mutex_);
150 record->snapshot.progress = value;
151 }
152 });
153 outcome = task->work(context);
154 } catch (const std::exception& error) {
155 outcome.status = Status::Failed;
156 outcome.diagnostics.push_back(ruleDiagnostic(eve::DiagnosticCode::Failed,
157 RuleId("editor.task.exception"),
158 DiagnosticSeverity::Error, error.what()));
159 } catch (...) {
160 outcome.status = Status::Failed;
161 outcome.diagnostics.push_back(ruleDiagnostic(eve::DiagnosticCode::Failed,
162 RuleId("editor.task.exception"),
163 DiagnosticSeverity::Error,
164 "Unknown worker exception"));
165 }
166
167 {
168 std::lock_guard lock(mutex_);
169 task->snapshot.output = std::move(outcome.output);
170 task->snapshot.diagnostics = std::move(outcome.diagnostics);
171 task->snapshot.progress = 1.0F;
172 if (task->cancelled->load(std::memory_order_relaxed) || outcome.status == Status::Cancelled)
173 task->snapshot.state = TaskState::Cancelled;
174 else if (outcome.status == Status::Applied || outcome.status == Status::NoOp)
175 task->snapshot.state = TaskState::Succeeded;
176 else
177 task->snapshot.state = TaskState::Failed;
178 if (task->discarded) tasks_.erase(task->snapshot.id);
179 }
180 task->work = {};
181 idle_.notify_all();
182 }
183}
184
185} // namespace eve::editing
ScriptComponentRecord record
Definition ECS.cpp:228
std::string name
Definition ECS.cpp:154
std::string id
std::shared_ptr< std::atomic< bool > > cancelled
std::string error
Definition Package.cpp:174
Object::Ptr value
bool found
const VegetationPresetContext & context
Move-only operation result carrying either a value or Status.
Definition Result.h:176
UUID-backed identifier adapter for legacy textual boundaries.
Definition Identity.h:313
void reportProgress(float progress) const
Publish normalized progress in the inclusive range 0..1.
bool isCancellationRequested() const
True after cancellation was requested.
Result< TaskId > submit(std::string name, Work work)
Queue background work and return its stable task identity.
Result< void > cancel(const TaskId &task)
Request cooperative cancellation of queued or running work.
TaskService()
Start the editor background worker.
std::function< TaskOutcome(const TaskContext &)> Work
Result< void > waitIdle(std::chrono::milliseconds timeout)
Wait until no task is queued or running; intended for shutdown and tests.
Result< void > discard(const TaskId &task)
Cancel and release an owned task, including already finished tasks. @ownership Caller relinquishes it...
~TaskService()
Cooperatively cancel pending work and join the worker.
Result< TaskSnapshot > snapshot(const TaskId &task) const
Return a thread-safe task snapshot.
StrongId< RuleIdTag > RuleId
Definition EditingIds.h:60
StrongId< TaskIdTag > TaskId
Definition EditingIds.h:70
Diagnostic ruleDiagnostic(eve::DiagnosticCode code, RuleId rule, DiagnosticSeverity severity, std::string message)
Build an owning common diagnostic carrying an open editing rule identity.