Repository navigation
Expand file tree
/
Copy pathProgramSession.cpp
More file actions
661 lines (570 loc) · 23.7 KB
/
Copy pathProgramSession.cpp
File metadata and controls
661 lines (570 loc) · 23.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
/* Program Session
*
* From: https://github.com/PokemonAutomation/
*
*/
#include <format>
#include <future>
#include "Common/Cpp/Exceptions.h"
#include "Common/Cpp/PanicDump.h"
#include "Common/Cpp/ScopeExit.h"
#include "Common/Cpp/Logging/GlobalLogger.h"
#include "CommonFramework/GlobalSettingsPanel.h"
#include "CommonFramework/Logging/Logger.h"
#include "CommonFramework/Exceptions/FatalProgramException.h"
#include "CommonFramework/Exceptions/ProgramFinishedException.h"
#include "CommonFramework/Exceptions/OperationFailedException.h"
#include "CommonFramework/Exceptions/OperationFailedExceptionWithScreenshot.h"
#include "CommonFramework/Options/Environment/SleepSuppressOption.h"
#include "CommonFramework/ProgramSession.h"
#include "CommonFramework/ProgramStats/StatsDatabase.h"
#include "CommonFramework/Notifications/ProgramInfo.h"
#include "CommonFramework/Notifications/ProgramNotifications.h"
#include "CommonFramework/Panels/ProgramDescriptor.h"
#include "CommonFramework/Tools/GlobalThreadPools.h"
#include "CommonFramework/ResourceDownload/ProgramMissingResourceTracker.h"
#include "CommonFramework/ResourceDownload/GlobalResourceDownloadManager.h"
#include "CommonFramework/ResourceDownload/ResourceDownloadHelpers.h"
#include "Integrations/ProgramTracker.h"
namespace PokemonAutomation{
ProgramSession::RunningProgramScope::RunningProgramScope(ProgramSession& session)
: m_session(session)
{
std::lock_guard<Mutex> lg(session.m_lock);
if (session.m_scope != nullptr){
throw InternalProgramError(
&session.m_logger,
PA_CURRENT_FUNCTION,
"Program is already running."
);
}
session.m_scope = &m_scope;
}
ProgramSession::RunningProgramScope::~RunningProgramScope(){
{
std::lock_guard<Mutex> lg(m_session.m_lock);
m_session.m_scope = nullptr;
}
m_session.m_cv.notify_all();
}
void ProgramSession::add_listener(Listener& listener){
m_listeners.add(listener);
}
void ProgramSession::remove_listener(Listener& listener){
m_listeners.remove(listener);
}
ProgramSession::ProgramSession(const ProgramDescriptor& descriptor, RunRecordStore& run_records)
: m_descriptor(descriptor)
, m_instance_id(ProgramTracker::instance().add_program(*this))
, m_run_recorder(run_records, global_logger_raw())
// , m_logger(global_logger_raw(), "Program:" + std::to_string(m_instance_id))
, m_logger(m_run_recorder, "Program")
, m_last_state_change(current_time())
, m_state(ProgramState::STOPPED)
, m_scope(nullptr)
{
load_historical_stats();
try{
validate_resource_list();
}catch (FileException& e){
e.log(global_logger_tagged());
}
}
ProgramSession::~ProgramSession(){
ProgramTracker::instance().remove_program(m_instance_id);
// ProgramSession::request_program_stop();
// join_program_thread();
}
void ProgramSession::join_program_thread() noexcept{
m_program_thread.wait_and_ignore_exceptions();
}
const std::string& ProgramSession::identifier() const{
return m_descriptor.identifier();
}
std::string ProgramSession::current_stats() const{
std::lock_guard<Mutex> lg(m_lock);
if (m_current_stats){
return m_current_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN);
}
return "";
}
std::string ProgramSession::historical_stats() const{
std::lock_guard<Mutex> lg(m_lock);
if (m_historical_stats){
return m_historical_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN);
}
return "";
}
WallClock ProgramSession::last_state_change() const{
return m_last_state_change.load(std::memory_order_relaxed);
}
void ProgramSession::internal_stop_program(){
{
std::lock_guard<Mutex> lg(program_lock());
if (m_scope != nullptr){
m_scope->cancel(std::make_exception_ptr(ProgramCancelledException()));
}
}
wait_for_finish();
}
void ProgramSession::report_stats_changed(){
std::lock_guard<Mutex> lg(m_lock);
push_stats();
}
void ProgramSession::report_error(const std::string& message){
std::lock_guard<Mutex> lg(m_lock);
push_error(message);
}
void ProgramSession::validate_resource_list(){
const std::unordered_set<std::string>& master_list = all_resource_names();
for (const std::string& resource_string : m_descriptor.required_resources()){
if (!master_list.contains(resource_string)){
throw InternalProgramError(
nullptr,
PA_CURRENT_FUNCTION,
"validate_resource_list(): Invalid resource in descriptor."
);
}
}
}
void ProgramSession::report_download_error(const std::string& message){
std::lock_guard<Mutex> lg(m_lock);
push_download_error(message);
}
void ProgramSession::report_download_added(std::shared_ptr<ResourceDownload> download_ptr){
// std::lock_guard<Mutex> lg(m_lock);
m_listeners.run_method(&Listener::download_added, std::move(download_ptr));
}
void ProgramSession::report_all_downloads_done(){
m_listeners.run_method(&Listener::all_downloads_done);
}
void ProgramSession::set_state(ProgramState state){
switch (state){
case ProgramState::NOT_READY:
m_logger.log("Program State: NOT_READY");
break;
case ProgramState::STOPPED:
m_logger.log("Program State: STOPPED");
break;
case ProgramState::RUNNING:
m_logger.log("Program State: RUNNING");
break;
case ProgramState::STOPPING:
m_logger.log("Program State: STOPPING");
break;
}
m_state.store(state, std::memory_order_relaxed);
m_listeners.run_method(&Listener::state_change, state);
}
void ProgramSession::push_stats(){
m_listeners.run_method(
&Listener::stats_update,
m_current_stats.get(),
m_historical_stats.get()
);
}
void ProgramSession::push_error(const std::string& message){
m_listeners.run_method(&Listener::error, message);
// A diagnostic in the run's record, not its outcome: the stats-save
// error and the download warnings come through here too.
m_run_recorder.event({.kind = "error", .text = message});
}
void ProgramSession::push_download_error(const std::string& message){
m_listeners.run_method(&Listener::download_error, message);
}
void ProgramSession::load_historical_stats(){
// Load historical stats.
std::unique_ptr<StatsTracker> stats = m_descriptor.make_stats();
if (stats){
m_logger.log("Loading historical stats...");
// m_current_stats = m_descriptor.make_stats();
StatSet set;
set.open_from_file(GlobalSettings::instance().STATS_FILE);
const std::string& identifier = m_descriptor.identifier();
StatList& list = set[identifier];
if (list.size() != 0){
list.aggregate(*stats);
}
m_historical_stats = std::move(stats);
}
}
void ProgramSession::update_historical_stats_with_current(){
if (m_current_stats){
m_logger.log("Saving historical stats...");
bool ok = StatSet::update_file(
GlobalSettings::instance().STATS_FILE,
m_descriptor.identifier(),
*m_current_stats
);
if (ok){
m_logger.log("Stats successfully saved!", COLOR_BLUE);
}else{
m_logger.log("Unable to save stats.", COLOR_RED);
push_error("Unable to save stats.");
}
}
}
std::string ProgramSession::start_program(){
m_logger.log("Received Program Start Request");
std::lock_guard<Mutex> lg(m_lock);
ProgramState state = this->current_state();
switch (state){
case ProgramState::NOT_READY:
m_logger.log("Program is not ready.", COLOR_RED);
return "Program is not ready.";
case ProgramState::STOPPED:
return start_accepted_run();
case ProgramState::RUNNING:
m_logger.log("Program is already running.", COLOR_RED);
return "Program is already running.";
case ProgramState::STOPPING:
m_logger.log("Program is currently stopping.", COLOR_RED);
return "Program is currently stopping.";
}
throw InternalProgramError(
&m_logger,
PA_CURRENT_FUNCTION,
"Invalid State: " + std::to_string((int)state)
);
}
std::string ProgramSession::stop_program(){
m_logger.log("Received Stop Request");
{
std::lock_guard<Mutex> lg(m_lock);
ProgramState state = this->current_state();
switch (state){
case ProgramState::NOT_READY:
m_logger.log("Program is not ready.", COLOR_RED);
return "Program is not ready.";
case ProgramState::STOPPED:
m_logger.log("Program is already stopped.", COLOR_RED);
return "Program is already stopped.";
case ProgramState::RUNNING:
m_logger.log("Stopping program...");
set_state(ProgramState::STOPPING);
m_run_recorder.stopping();
break;
case ProgramState::STOPPING:
m_logger.log("Program is already stopping.", COLOR_RED);
return "Program is already stopping.";
default:
throw InternalProgramError(
&m_logger,
PA_CURRENT_FUNCTION,
"Invalid State: " + std::to_string((int)state)
);
}
}
internal_stop_program();
m_last_state_change.store(current_time(), std::memory_order_relaxed);
return "";
}
// Under the lock, for a stopped session: checks the settings, then starts
// the program thread. The run is accepted here: its record exists before
// the program thread can report anything.
std::string ProgramSession::start_accepted_run(){
std::string error = check_validity();
if (!error.empty()){
m_logger.log(error, COLOR_RED);
return error;
}
// Wait for previous program thread to finish.
join_program_thread();
m_logger.log("Starting program...");
m_last_state_change.store(current_time(), std::memory_order_relaxed);
m_run_recorder.begin(identifier(), settings_json());
set_state(ProgramState::RUNNING);
try{
m_program_thread = dispatch_program_thread([this]{
run_with_catch(
"ProgramSession::start_program()",
[this]{ run_program_and_record(); }
);
});
}catch (Exception& e){
return abandon_run(std::format("The program thread could not be started: {}", e.message()));
}catch (std::exception& e){
return abandon_run(std::format("The program thread could not be started: {}", e.what()));
}
return "";
}
// No thread, so no run: closes the record and leaves the session stopped,
// so the next start can try again. Returns `message` for start_program().
std::string ProgramSession::abandon_run(std::string message){
m_logger.log(message, COLOR_RED);
m_run_recorder.finish({.outcome = RunOutcome::FAILED, .error = message});
set_state(ProgramState::STOPPED);
return message;
}
AsyncTask ProgramSession::dispatch_program_thread(std::function<void()> body){
return GlobalThreadPools::unlimited_realtime().dispatch_now_blocking(std::move(body));
}
void ProgramSession::run_program_and_record(){
// Exactly one result per run: whichever way the thread leaves, the
// record is closed, and a path that set none is a failure, never a
// success. An exception that escapes run_program() (as today it does
// for a validity check that fails after the start) is its result.
std::optional<RunResult> result;
ScopeExit finish_run([&]{
m_run_recorder.finish(result.value_or(RunResult{
.outcome = RunOutcome::FAILED,
.error = "The program thread ended without a result.",
}));
});
try{
result = run_program();
}catch (Exception& e){
result = RunResult{.outcome = RunOutcome::FAILED, .error = e.message().empty() ? e.name() : e.message()};
throw;
}catch (std::exception& e){
result = RunResult{.outcome = RunOutcome::FAILED, .error = e.what()};
throw;
}
}
// Under the lock: false when the run was stopped before the thread got
// going. Throws when the settings are no longer valid. Loads the stats.
bool ProgramSession::prepare_run(){
std::lock_guard<Mutex> lg(m_lock);
if (current_state() != ProgramState::RUNNING){
return false;
}
std::string error = check_validity();
if (!error.empty()){
throw UserSetupError(logger(), std::move(error));
}
m_current_stats = m_descriptor.make_stats();
load_historical_stats();
push_stats();
return true;
}
// The run's result when the resources it needs could not be downloaded.
std::optional<RunResult> ProgramSession::download_resources(){
if (download_prereqs(*m_scope)){
return std::nullopt;
}
// The details were reported as "error" events. A stop during the
// download is a cancellation, not a failure.
if (current_state() == ProgramState::STOPPING){
return RunResult{.outcome = RunOutcome::CANCELLED};
}
return RunResult{.outcome = RunOutcome::FAILED, .error = "A required resource could not be downloaded."};
}
void ProgramSession::end_run(){
std::lock_guard<Mutex> lg(m_lock);
push_stats();
update_historical_stats_with_current();
set_state(ProgramState::STOPPED);
}
RunResult ProgramSession::run_program(){
SleepSuppressScope sleep_scope(GlobalSettings::instance().SLEEP_SUPPRESS->PROGRAM_RUNNING);
RunResult result;
if (!prepare_run()){
return {.outcome = RunOutcome::CANCELLED};
}
m_instance->options().reset_state();
ProgramInfo program_info(
identifier(),
m_descriptor.category(),
m_descriptor.display_name(),
last_state_change()
);
{
RunningProgramScope running_scope(*this);
if (std::optional<RunResult> failed = download_resources()){
return *failed;
}
std::unique_ptr<ProgramEnvironment> env = make_env(program_info);
try{
logger().log("<b>Starting Program: " + identifier() + "</b>");
env->log_to_ui("- Starting Program -");
m_instance->run_start_program_checks(m_descriptor, *env);
internal_run_program(*env);
env->log_to_ui("- Program Finished -");
logger().log("Program finished normally!", COLOR_BLUE);
result.outcome = RunOutcome::COMPLETED;
}catch (OperationCancelledException&){
env->log_to_ui("- Program Stopped -");
result.outcome = RunOutcome::CANCELLED;
}catch (ProgramCancelledException&){
env->log_to_ui("- Program Stopped -");
result.outcome = RunOutcome::CANCELLED;
}catch (ProgramFinishedException& e){
logger().log("Program finished early!", COLOR_BLUE);
env->log_to_ui("- Program Finished -");
send_program_finished_notification(
*env, m_instance->NOTIFICATION_PROGRAM_FINISH,
e.message(),
e.screenshot_view()
);
result.outcome = RunOutcome::COMPLETED;
result.frame = e.screenshot();
}catch (InvalidConnectionStateException& e){
logger().log("Program stopped due to connection issue.", COLOR_RED);
env->log_to_ui("- Invalid Connection -", COLOR_RED);
std::string message = e.message();
if (message.empty()){
message = e.name();
}
report_error(message);
result.error = message;
}catch (FatalProgramException& e){
logger().log("Program stopped with an exception!", COLOR_RED);
env->log_to_ui("- Program Error -", COLOR_RED);
std::string message = e.message();
if (message.empty()){
message = e.name();
}
report_error(message);
e.send_fatal_error_notif_and_telemetry_report(*env, m_instance->NOTIFICATION_ERROR_FATAL);
result.error = message;
result.frame = e.screenshot();
}catch (OperationFailedExceptionWithScreenshot& e){
logger().log("Program stopped with an exception!", COLOR_RED);
env->log_to_ui("- Program Error -", COLOR_RED);
std::string message = e.message();
if (message.empty()){
message = e.name();
}
report_error(message);
e.send_fatal_error_notif_and_telemetry_report(*env, m_instance->NOTIFICATION_ERROR_FATAL);
result.error = message;
result.frame = e.screenshot();
}catch (OperationFailedException& e){ // no screenshot
logger().log("Program stopped with an exception!", COLOR_RED);
env->log_to_ui("- Program Error -", COLOR_RED);
std::string message = e.message();
if (message.empty()){
message = e.name();
}
report_error(message);
e.send_fatal_error_notif_and_telemetry_report(*env, m_instance->NOTIFICATION_ERROR_FATAL);
result.error = message;
}catch (Exception& e){
logger().log("Program stopped with an exception!", COLOR_RED);
env->log_to_ui("- Program Error -", COLOR_RED);
std::string message = e.message();
if (message.empty()){
message = e.name();
}
report_error(message);
send_program_fatal_error_notification(
*env, m_instance->NOTIFICATION_ERROR_FATAL,
message
);
result.error = message;
}catch (std::exception& e){
logger().log("Program stopped with an exception!", COLOR_RED);
env->log_to_ui("- Program Error -", COLOR_RED);
std::string message = e.what();
if (message.empty()){
message = "Unknown std::exception.";
}
report_error(message);
send_program_fatal_error_notification(
*env, m_instance->NOTIFICATION_ERROR_FATAL,
message
);
result.error = message;
}catch (...){
logger().log("Program stopped with an exception!", COLOR_RED);
env->log_to_ui("- Unknown Error -", COLOR_RED);
report_error("Unknown error.");
send_program_fatal_error_notification(
*env, m_instance->NOTIFICATION_ERROR_FATAL,
"Unknown error."
);
result.error = "Unknown error.";
}
}
end_run();
return result;
}
RequiredResourceResult ProgramSession::find_missing_resources(){
bool upgrade_warning = false;
std::vector<std::string> missing_resources;
for(const std::string& resource_type : m_descriptor.required_resources()){
ResourceVersionStatus version_status = get_local_version_info(resource_type).version_status;
switch(version_status){
case ResourceVersionStatus::CURRENT:
// we have this resource, check the next one
continue;
case ResourceVersionStatus::FUTURE_VERSION:
// we have this resource, check the next one
// however, the resource that was downloaded is more updated than what the program is expecting
// warn the user to upgrade CC.
upgrade_warning = true;
continue;
case ResourceVersionStatus::OUTDATED:
case ResourceVersionStatus::NOT_APPLICABLE:{
// we don't have the resource. check remote to see if correct version is available.
DownloadedResourceMetadata remote_resource = get_remote_resource_metadata_from_resource_slug(resource_type);
DownloadedResourceMetadata expected_resource = get_expected_resource_metadata_from_resource_slug(resource_type);
uint16_t expected_version_num = expected_resource.version_num.value();
uint16_t remote_version_num = remote_resource.version_num.value();
if (expected_version_num < remote_version_num){
// remote version is more updated than we expect
// warn the user to upgrade CC.
upgrade_warning = true;
}else if (expected_version_num > remote_version_num){
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "resources_to_download: expected_version_num > remote_version_num. This shouldn't happen.");
}
missing_resources.emplace_back(remote_resource.resource_name);
break;
}
default:
throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "resources_to_download: Unknown enum.");
}
}
return RequiredResourceResult{std::move(missing_resources), upgrade_warning};
}
bool ProgramSession::download_prereqs(CancellableScope& scope){
try{
auto [missing_resources, requires_upgrade] = find_missing_resources();
if (requires_upgrade){
std::string warning_string =
"The program is expecting an older version of a resource than is available. "
"This likely means that your version of Computer Control is out of date. "
"We recommend that you upgrade the Computer Control program.";
report_error(warning_string);
// cout << warning_string << endl;
}
if (missing_resources.empty()){
// cout << "required_download_list is empty. Start the program." << endl;
return true;
}
// 1. Create a C++ standard promise to hold the final boolean result
std::promise<bool> download_promise;
std::future<bool> download_future = download_promise.get_future();
// ProgramMissingResourceTracker is responsible for calling report_error() if
// the download fails, or if exceptions are thrown within the download.
ProgramMissingResourceTracker missing_resource_tracker(scope, download_promise, *this);
GlobalResourceDownloadManager& global_download_manager = GlobalResourceDownloadManager::instance();
for (const std::string& resource_slug : missing_resources){
// cout << download_ptr->get_name() << endl;
auto download_ptr = global_download_manager.add_to_download_list(resource_slug);
if (!download_ptr){
std::cerr << "Error: Null download pointer for " << resource_slug << std::endl;
continue;
}
missing_resource_tracker.add_resource(download_ptr);
report_download_added(download_ptr);
}
missing_resource_tracker.finalize_initial_batch();
// Block until the ProgramMissingResourceTracker calls set_value(),
// when the downloads all succeed, or one fails, or the user clicks "Stop Program"
bool success = download_future.get();
report_all_downloads_done();
return success;
}catch(OperationFailedException& e){
report_error(e.message());
}catch(InternalProgramError& e){
report_error(e.message());
}catch (const std::exception& e){
std::string message = std::string(e.what()) + "Report this as an error.";
report_error(message);
}catch(...){
report_error("show_download_prereqs_popup: Unknown exception caught. Report this as an error.");
}
return false;
}
}