summaryrefslogtreecommitdiffstats
path: root/api/logic/minecraft/ComponentUpdateTask.cpp
blob: e03318c57622fd68de60a6425ba4c415d6c37746 (plain)
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
#include "ComponentUpdateTask.h"

#include "ComponentList_p.h"
#include "ComponentList.h"
#include "Component.h"
#include <Env.h>
#include <meta/Index.h>
#include <meta/VersionList.h>
#include <meta/Version.h>
#include "ComponentUpdateTask_p.h"
#include <cassert>
#include <Version.h>
#include "net/Mode.h"
#include "OneSixVersionFormat.h"

/*
 * This is responsible for loading the components of a component list AND resolving dependency issues between them
 */

/*
 * FIXME: the 'one shot async task' nature of this does not fit the intended usage
 * Really, it should be a reactor/state machine that receives input from the application
 * and dynamically adapts to changing requirements...
 *
 * The reactor should be the only entry into manipulating the ComponentList.
 * See: https://en.wikipedia.org/wiki/Reactor_pattern
 */

/*
 * Or make this operate on a snapshot of the ComponentList state, then merge results in as long as the snapshot and ComponentList didn't change?
 * If the component list changes, start over.
 */

ComponentUpdateTask::ComponentUpdateTask(Mode mode, Net::Mode netmode, ComponentList* list, QObject* parent)
	: Task(parent)
{
	d.reset(new ComponentUpdateTaskData);
	d->m_list = list;
	d->mode = mode;
	d->netmode = netmode;
}

ComponentUpdateTask::~ComponentUpdateTask()
{
}

void ComponentUpdateTask::executeTask()
{
	qDebug() << "Loading components";
	loadComponents();
}

namespace
{
enum class LoadResult
{
	LoadedLocal,
	RequiresRemote,
	Failed
};

LoadResult composeLoadResult(LoadResult a, LoadResult b)
{
	if (a < b)
	{
		return b;
	}
	return a;
}

static LoadResult loadComponent(ComponentPtr component, shared_qobject_ptr<Task>& loadTask, Net::Mode netmode)
{
	if(component->m_loaded)
	{
		qDebug() << component->getName() << "is already loaded";
		return LoadResult::LoadedLocal;
	}

	LoadResult result = LoadResult::Failed;
	auto customPatchFilename = component->getFilename();
	if(QFile::exists(customPatchFilename))
	{
		// if local file exists...

		// check for uid problems inside...
		bool fileChanged = false;
		auto file = ProfileUtils::parseJsonFile(QFileInfo(customPatchFilename), false);
		if(file->uid != component->m_uid)
		{
			file->uid = component->m_uid;
			fileChanged = true;
		}
		if(fileChanged)
		{
			// FIXME: @QUALITY do not ignore return value
			ProfileUtils::saveJsonFile(OneSixVersionFormat::versionFileToJson(file), customPatchFilename);
		}

		component->m_file = file;
		component->m_loaded = true;
		result = LoadResult::LoadedLocal;
	}
	else
	{
		auto metaVersion = ENV.metadataIndex()->get(component->m_uid, component->m_version);
		component->m_metaVersion = metaVersion;
		if(metaVersion->isLoaded())
		{
			component->m_loaded = true;
			result = LoadResult::LoadedLocal;
		}
		else
		{
			metaVersion->load(netmode);
			loadTask = metaVersion->getCurrentTask();
			if(loadTask)
				result = LoadResult::RequiresRemote;
			else if (metaVersion->isLoaded())
				result = LoadResult::LoadedLocal;
			else
				result = LoadResult::Failed;
		}
	}
	return result;
}

static LoadResult loadComponentList(ComponentPtr component, shared_qobject_ptr<Task>& loadTask, Net::Mode netmode)
{
	if(component->m_loaded)
	{
		qDebug() << component->getName() << "is already loaded";
		return LoadResult::LoadedLocal;
	}

	LoadResult result = LoadResult::Failed;
	auto metaList = ENV.metadataIndex()->get(component->m_uid);
	if(metaList->isLoaded())
	{
		component->m_loaded = true;
		result = LoadResult::LoadedLocal;
	}
	else
	{
		metaList->load(netmode);
		loadTask = metaList->getCurrentTask();
		result = LoadResult::RequiresRemote;
	}
	return result;
}

static LoadResult loadIndex(shared_qobject_ptr<Task>& loadTask, Net::Mode netmode)
{
	// FIXME: DECIDE. do we want to run the update task anyway?
	if(ENV.metadataIndex()->isLoaded())
	{
		qDebug() << "Index is already loaded";
		return LoadResult::LoadedLocal;
	}
	ENV.metadataIndex()->load(netmode);
	loadTask = ENV.metadataIndex()->getCurrentTask();
	if(loadTask)
	{
		return LoadResult::RequiresRemote;
	}
	// FIXME: this is assuming the load succeeded... did it really?
	return LoadResult::LoadedLocal;
}
}

void ComponentUpdateTask::loadComponents()
{
	LoadResult result = LoadResult::LoadedLocal;
	size_t taskIndex = 0;
	size_t componentIndex = 0;
	d->remoteLoadSuccessful = true;
	// load the main index (it is needed to determine if components can revert)
	{
		// FIXME: tear out as a method? or lambda?
		shared_qobject_ptr<Task> indexLoadTask;
		auto singleResult = loadIndex(indexLoadTask, d->netmode);
		result = composeLoadResult(result, singleResult);
		if(indexLoadTask)
		{
			qDebug() << "Remote loading is being run for metadata index";
			RemoteLoadStatus status;
			status.type = RemoteLoadStatus::Type::Index;
			d->remoteLoadStatusList.append(status);
			connect(indexLoadTask.get(), &Task::succeeded, [=]()
			{
				remoteLoadSucceeded(taskIndex);
			});
			connect(indexLoadTask.get(), &Task::failed, [=](const QString & error)
			{
				remoteLoadFailed(taskIndex, error);
			});
			taskIndex++;
		}
	}
	// load all the components OR their lists...
	for (auto component: d->m_list->d->components)
	{
		shared_qobject_ptr<Task> loadTask;
		LoadResult singleResult;
		RemoteLoadStatus::Type loadType;
		// FIXME: to do this right, we need to load the lists and decide on which versions to use during dependency resolution. For now, ignore all that...
#if 0
		switch(d->mode)
		{
			case Mode::Launch:
			{
				singleResult = loadComponent(component, loadTask, d->netmode);
				loadType = RemoteLoadStatus::Type::Version;
				break;
			}
			case Mode::Resolution:
			{
				singleResult = loadComponentList(component, loadTask, d->netmode);
				loadType = RemoteLoadStatus::Type::List;
				break;
			}
		}
#else
		singleResult = loadComponent(component, loadTask, d->netmode);
		loadType = RemoteLoadStatus::Type::Version;
#endif
		if(singleResult == LoadResult::LoadedLocal)
		{
			component->updateCachedData();
		}
		result = composeLoadResult(result, singleResult);
		if (loadTask)
		{
			qDebug() << "Remote loading is being run for" << component->getName();
			connect(loadTask.get(), &Task::succeeded, [=]()
			{
				remoteLoadSucceeded(taskIndex);
			});
			connect(loadTask.get(), &Task::failed, [=](const QString & error)
			{
				remoteLoadFailed(taskIndex, error);
			});
			RemoteLoadStatus status;
			status.type = loadType;
			status.componentListIndex = componentIndex;
			d->remoteLoadStatusList.append(status);
			taskIndex++;
		}
		componentIndex++;
	}
	d->remoteTasksInProgress = taskIndex;
	switch(result)
	{
		case LoadResult::LoadedLocal:
		{
			// Everything got loaded. Advance to dependency resolution.
			resolveDependencies(d->mode == Mode::Launch || d->netmode == Net::Mode::Offline);
			break;
		}
		case LoadResult::RequiresRemote:
		{
			// we wait for signals.
			break;
		}
		case LoadResult::Failed:
		{
			emitFailed(tr("Some component metadata load tasks failed."));
			break;
		}
	}
}

namespace
{
	struct RequireEx : public Meta::Require
	{
		size_t indexOfFirstDependee = 0;
	};
	struct RequireCompositionResult
	{
		bool ok;
		RequireEx outcome;
	};
	using RequireExSet = std::set<RequireEx>;
}

static RequireCompositionResult composeRequirement(const RequireEx & a, const RequireEx & b)
{
	assert(a.uid == b.uid);
	RequireEx out;
	out.uid = a.uid;
	out.indexOfFirstDependee = std::min(a.indexOfFirstDependee, b.indexOfFirstDependee);
	if(a.equalsVersion.isEmpty())
	{
		out.equalsVersion = b.equalsVersion;
	}
	else if (b.equalsVersion.isEmpty())
	{
		out.equalsVersion = a.equalsVersion;
	}
	else if (a.equalsVersion == b.equalsVersion)
	{
		out.equalsVersion = a.equalsVersion;
	}
	else
	{
		// FIXME: mark error as explicit version conflict
		return {false, out};
	}

	if(a.suggests.isEmpty())
	{
		out.suggests = b.suggests;
	}
	else if (b.suggests.isEmpty())
	{
		out.suggests = a.suggests;
	}
	else
	{
		Version aVer(a.suggests);
		Version bVer(b.suggests);
		out.suggests = (aVer < bVer ? b.suggests : a.suggests);
	}
	return {true, out};
}

// gather the requirements from all components, finding any obvious conflicts
static bool gatherRequirementsFromComponents(const ComponentContainer & input, RequireExSet & output)
{
	bool succeeded = true;
	size_t componentNum = 0;
	for(auto component: input)
	{
		auto &componentRequires = component->m_cachedRequires;
		for(const auto & componentRequire: componentRequires)
		{
			auto found = std::find_if(output.cbegin(), output.cend(), [componentRequire](const Meta::Require & req){
				return req.uid == componentRequire.uid;
			});

			RequireEx componenRequireEx;
			componenRequireEx.uid = componentRequire.uid;
			componenRequireEx.suggests = componentRequire.suggests;
			componenRequireEx.equalsVersion = componentRequire.equalsVersion;
			componenRequireEx.indexOfFirstDependee = componentNum;

			if(found != output.cend())
			{
				// found... process it further
				auto result = composeRequirement(componenRequireEx, *found);
				if(result.ok)
				{
					output.erase(componenRequireEx);
					output.insert(result.outcome);
				}
				else
				{
					qCritical()
						<< "Conflicting requirements:"
						<< componentRequire.uid
						<< "versions:"
						<< componentRequire.equalsVersion
						<< ";"
						<< (*found).equalsVersion;
				}
				succeeded &= result.ok;
			}
			else
			{
				// not found, accumulate
				output.insert(componenRequireEx);
			}
		}
		componentNum++;
	}
	return succeeded;
}

/// Get list of uids that can be trivially removed because nothing is depending on them anymore (and they are installed as deps)
static void getTrivialRemovals(const ComponentContainer & components, const RequireExSet & reqs, QStringList &toRemove)
{
	for(const auto & component: components)
	{
		if(!component->m_dependencyOnly)
			continue;
		if(!component->m_cachedVolatile)
			continue;
		RequireEx reqNeedle;
		reqNeedle.uid = component->m_uid;
		const auto iter = reqs.find(reqNeedle);
		if(iter == reqs.cend())
		{
			toRemove.append(component->m_uid);
		}
	}
}

/**
 * handles:
 * - trivial addition (there is an unmet requirement and it can be trivially met by adding something)
 * - trivial version conflict of dependencies == explicit version required and installed is different
 *
 * toAdd - set of requirements than mean adding a new component
 * toChange - set of requirements that mean changing version of an existing component
 */
static bool getTrivialComponentChanges(const ComponentIndex & index, const RequireExSet & input, RequireExSet & toAdd, RequireExSet & toChange)
{
	enum class Decision
	{
		Undetermined,
		Met,
		Missing,
		VersionNotSame,
		LockedVersionNotSame
	} decision = Decision::Undetermined;

	QString reqStr;
	bool succeeded = true;
	// list the composed requirements and say if they are met or unmet
	for(auto & req: input)
	{
		do
		{
			if(req.equalsVersion.isEmpty())
			{
				reqStr = QString("Req: %1").arg(req.uid);
				if(index.contains(req.uid))
				{
					decision = Decision::Met;
				}
				else
				{
					toAdd.insert(req);
					decision = Decision::Missing;
				}
				break;
			}
			else
			{
				reqStr = QString("Req: %1 == %2").arg(req.uid, req.equalsVersion);
				const auto & compIter = index.find(req.uid);
				if(compIter == index.cend())
				{
					toAdd.insert(req);
					decision = Decision::Missing;
					break;
				}
				auto & comp = (*compIter);
				if(comp->getVersion() != req.equalsVersion)
				{
					if(comp->m_dependencyOnly)
					{
						decision = Decision::VersionNotSame;
					}
					else
					{
						decision = Decision::LockedVersionNotSame;
					}
					break;
				}
				decision = Decision::Met;
			}
		} while(false);
		switch(decision)
		{
			case Decision::Undetermined:
				qCritical() << "No decision for" << reqStr;
				succeeded = false;
				break;
			case Decision::Met:
				qDebug() << reqStr << "Is met.";
				break;
			case Decision::Missing:
				qDebug() << reqStr << "Is missing and should be added at" << req.indexOfFirstDependee;
				toAdd.insert(req);
				break;
			case Decision::VersionNotSame:
				qDebug() << reqStr << "already has different version that can be changed.";
				toChange.insert(req);
				break;
			case Decision::LockedVersionNotSame:
				qDebug() << reqStr << "already has different version that cannot be changed.";
				succeeded = false;
				break;
		}
	}
	return succeeded;
}

// FIXME, TODO: decouple dependency resolution from loading
// FIXME: This works directly with the ComponentList internals. It shouldn't! It needs richer data types than ComponentList uses.
// FIXME: throw all this away and use a graph
void ComponentUpdateTask::resolveDependencies(bool checkOnly)
{
	qDebug() << "Resolving dependencies";
	/*
	 * this is a naive dependency resolving algorithm. all it does is check for following conditions and react in simple ways:
	 * 1. There are conflicting dependencies on the same uid with different exact version numbers
	 *    -> hard error
	 * 2. A dependency has non-matching exact version number
	 *    -> hard error
	 * 3. A dependency is entirely missing and needs to be injected before the dependee(s)
	 *    -> requirements are injected
	 *
	 * NOTE: this is a placeholder and should eventually be replaced with something 'serious'
	 */
	auto & components = d->m_list->d->components;
	auto & componentIndex = d->m_list->d->componentIndex;

	RequireExSet allRequires;
	QStringList toRemove;
	do
	{
		allRequires.clear();
		toRemove.clear();
		if(!gatherRequirementsFromComponents(components, allRequires))
		{
			emitFailed(tr("Conflicting requirements detected during dependency checking!"));
			return;
		}
		getTrivialRemovals(components, allRequires, toRemove);
		if(!toRemove.isEmpty())
		{
			qDebug() << "Removing obsolete components...";
			for(auto & remove : toRemove)
			{
				qDebug() << "Removing" << remove;
				d->m_list->remove(remove);
			}
		}
	} while (!toRemove.isEmpty());
	RequireExSet toAdd;
	RequireExSet toChange;
	bool succeeded = getTrivialComponentChanges(componentIndex, allRequires, toAdd, toChange);
	if(!succeeded)
	{
		emitFailed(tr("Instance has conflicting dependencies."));
		return;
	}
	if(checkOnly)
	{
		if(toAdd.size() || toChange.size())
		{
			emitFailed(tr("Instance has unresolved dependencies while loading/checking for launch."));
		}
		else
		{
			emitSucceeded();
		}
		return;
	}

	bool recursionNeeded = false;
	if(toAdd.size())
	{
		// add stuff...
		for(auto &add: toAdd)
		{
			ComponentPtr component = new Component(d->m_list, add.uid);
			if(!add.equalsVersion.isEmpty())
			{
				// exact version
				qDebug() << "Adding" << add.uid << "version" << add.equalsVersion << "at position" << add.indexOfFirstDependee;
				component->m_version = add.equalsVersion;
			}
			else
			{
				// version needs to be decided
				qDebug() << "Adding" << add.uid << "at position" << add.indexOfFirstDependee;
// ############################################################################################################
// HACK HACK HACK HACK FIXME: this is a placeholder for deciding what version to use. For now, it is hardcoded.
				if(!add.suggests.isEmpty())
				{
					component->m_version = add.suggests;
				}
				else
				{
					if(add.uid == "org.lwjgl")
					{
						component->m_version = "2.9.1";
					}
					else if (add.uid == "org.lwjgl3")
					{
						component->m_version = "3.1.2";
					}
				}
// HACK HACK HACK HACK FIXME: this is a placeholder for deciding what version to use. For now, it is hardcoded.
// ############################################################################################################
			}
			component->m_dependencyOnly = true;
			// FIXME: this should not work directly with the component list
			d->m_list->insertComponent(add.indexOfFirstDependee, component);
			componentIndex[add.uid] = component;
		}
		recursionNeeded = true;
	}
	if(toChange.size())
	{
		// change a version of something that exists
		for(auto &change: toChange)
		{
			// FIXME: this should not work directly with the component list
			qDebug() << "Setting version of " << change.uid << "to" << change.equalsVersion;
			auto component = componentIndex[change.uid];
			component->setVersion(change.equalsVersion);
		}
		recursionNeeded = true;
	}

	if(recursionNeeded)
	{
		loadComponents();
	}
	else
	{
		emitSucceeded();
	}
}

void ComponentUpdateTask::remoteLoadSucceeded(size_t taskIndex)
{
	auto &taskSlot = d->remoteLoadStatusList[taskIndex];
	if(taskSlot.finished)
	{
		qWarning() << "Got multiple results from remote load task" << taskIndex;
		return;
	}
	qDebug() << "Remote task" << taskIndex << "succeeded";
	taskSlot.succeeded = false;
	taskSlot.finished = true;
	d->remoteTasksInProgress --;
	// update the cached data of the component from the downloaded version file.
	if (taskSlot.type == RemoteLoadStatus::Type::Version)
	{
		auto component = d->m_list->getComponent(taskSlot.componentListIndex);
		component->m_loaded = true;
		component->updateCachedData();
	}
	checkIfAllFinished();
}


void ComponentUpdateTask::remoteLoadFailed(size_t taskIndex, const QString& msg)
{
	auto &taskSlot = d->remoteLoadStatusList[taskIndex];
	if(taskSlot.finished)
	{
		qWarning() << "Got multiple results from remote load task" << taskIndex;
		return;
	}
	qDebug() << "Remote task" << taskIndex << "failed: " << msg;
	d->remoteLoadSuccessful = false;
	taskSlot.succeeded = false;
	taskSlot.finished = true;
	taskSlot.error = msg;
	d->remoteTasksInProgress --;
	checkIfAllFinished();
}

void ComponentUpdateTask::checkIfAllFinished()
{
	if(d->remoteTasksInProgress)
	{
		// not yet...
		return;
	}
	if(d->remoteLoadSuccessful)
	{
		// nothing bad happened... clear the temp load status and proceed with looking at dependencies
		d->remoteLoadStatusList.clear();
		resolveDependencies(d->mode == Mode::Launch);
	}
	else
	{
		// remote load failed... report error and bail
		QStringList allErrorsList;
		for(auto & item: d->remoteLoadStatusList)
		{
			if(!item.succeeded)
			{
				allErrorsList.append(item.error);
			}
		}
		auto allErrors = allErrorsList.join("\n");
		emitFailed(tr("Component metadata update task failed while downloading from remote server:\n%1").arg(allErrors));
		d->remoteLoadStatusList.clear();
	}
}