summaryrefslogtreecommitdiffstats
path: root/logic/net/HttpMetaCache.cpp
blob: 977e3a908e18b805485b0a724e72524d98c8b151 (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
/* Copyright 2013-2015 MultiMC Contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "Env.h"
#include "HttpMetaCache.h"
#include "FileSystem.h"
#include <pathutils.h>

#include <QFileInfo>
#include <QFile>
#include <QTemporaryFile>
#include <QDateTime>
#include <QCryptographicHash>

#include <QDebug>

#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>

QString MetaEntry::getFullPath()
{
	// FIXME: make local?
	return PathCombine(ENV.metacache()->getBasePath(base), path);
}

HttpMetaCache::HttpMetaCache(QString path) : QObject()
{
	m_index_file = path;
	saveBatchingTimer.setSingleShot(true);
	saveBatchingTimer.setTimerType(Qt::VeryCoarseTimer);
	connect(&saveBatchingTimer, SIGNAL(timeout()), SLOT(SaveNow()));
}

HttpMetaCache::~HttpMetaCache()
{
	saveBatchingTimer.stop();
	SaveNow();
}

MetaEntryPtr HttpMetaCache::getEntry(QString base, QString resource_path)
{
	// no base. no base path. can't store
	if (!m_entries.contains(base))
	{
		// TODO: log problem
		return MetaEntryPtr();
	}
	EntryMap &map = m_entries[base];
	if (map.entry_list.contains(resource_path))
	{
		return map.entry_list[resource_path];
	}
	return MetaEntryPtr();
}

MetaEntryPtr HttpMetaCache::resolveEntry(QString base, QString resource_path,
										 QString expected_etag)
{
	auto entry = getEntry(base, resource_path);
	// it's not present? generate a default stale entry
	if (!entry)
	{
		return staleEntry(base, resource_path);
	}

	auto &selected_base = m_entries[base];
	QString real_path = PathCombine(selected_base.base_path, resource_path);
	QFileInfo finfo(real_path);

	// is the file really there? if not -> stale
	if (!finfo.isFile() || !finfo.isReadable())
	{
		// if the file doesn't exist, we disown the entry
		selected_base.entry_list.remove(resource_path);
		return staleEntry(base, resource_path);
	}

	if (!expected_etag.isEmpty() && expected_etag != entry->etag)
	{
		// if the etag doesn't match expected, we disown the entry
		selected_base.entry_list.remove(resource_path);
		return staleEntry(base, resource_path);
	}

	// if the file changed, check md5sum
	qint64 file_last_changed = finfo.lastModified().toUTC().toMSecsSinceEpoch();
	if (file_last_changed != entry->local_changed_timestamp)
	{
		QFile input(real_path);
		input.open(QIODevice::ReadOnly);
		QString md5sum = QCryptographicHash::hash(input.readAll(), QCryptographicHash::Md5)
							 .toHex()
							 .constData();
		if (entry->md5sum != md5sum)
		{
			selected_base.entry_list.remove(resource_path);
			return staleEntry(base, resource_path);
		}
		// md5sums matched... keep entry and save the new state to file
		entry->local_changed_timestamp = file_last_changed;
		SaveEventually();
	}

	// entry passed all the checks we cared about.
	return entry;
}

bool HttpMetaCache::updateEntry(MetaEntryPtr stale_entry)
{
	if (!m_entries.contains(stale_entry->base))
	{
		qCritical() << "Cannot add entry with unknown base: "
					 << stale_entry->base.toLocal8Bit();
		return false;
	}
	if (stale_entry->stale)
	{
		qCritical() << "Cannot add stale entry: " << stale_entry->getFullPath().toLocal8Bit();
		return false;
	}
	m_entries[stale_entry->base].entry_list[stale_entry->path] = stale_entry;
	SaveEventually();
	return true;
}

bool HttpMetaCache::evictEntry(MetaEntryPtr entry)
{
	if(entry)
	{
		entry->stale = true;
		SaveEventually();
		return true;
	}
	return false;
}

MetaEntryPtr HttpMetaCache::staleEntry(QString base, QString resource_path)
{
	auto foo = new MetaEntry;
	foo->base = base;
	foo->path = resource_path;
	foo->stale = true;
	return MetaEntryPtr(foo);
}

void HttpMetaCache::addBase(QString base, QString base_root)
{
	// TODO: report error
	if (m_entries.contains(base))
		return;
	// TODO: check if the base path is valid
	EntryMap foo;
	foo.base_path = base_root;
	m_entries[base] = foo;
}

QString HttpMetaCache::getBasePath(QString base)
{
	if (m_entries.contains(base))
	{
		return m_entries[base].base_path;
	}
	return QString();
}

void HttpMetaCache::Load()
{
	QFile index(m_index_file);
	if (!index.open(QIODevice::ReadOnly))
		return;

	QJsonDocument json = QJsonDocument::fromJson(index.readAll());
	if (!json.isObject())
		return;
	auto root = json.object();
	// check file version first
	auto version_val = root.value("version");
	if (!version_val.isString())
		return;
	if (version_val.toString() != "1")
		return;

	// read the entry array
	auto entries_val = root.value("entries");
	if (!entries_val.isArray())
		return;
	QJsonArray array = entries_val.toArray();
	for (auto element : array)
	{
		if (!element.isObject())
			return;
		auto element_obj = element.toObject();
		QString base = element_obj.value("base").toString();
		if (!m_entries.contains(base))
			continue;
		auto &entrymap = m_entries[base];
		auto foo = new MetaEntry;
		foo->base = base;
		QString path = foo->path = element_obj.value("path").toString();
		foo->md5sum = element_obj.value("md5sum").toString();
		foo->etag = element_obj.value("etag").toString();
		foo->local_changed_timestamp = element_obj.value("last_changed_timestamp").toDouble();
		foo->remote_changed_timestamp =
			element_obj.value("remote_changed_timestamp").toString();
		// presumed innocent until closer examination
		foo->stale = false;
		entrymap.entry_list[path] = MetaEntryPtr(foo);
	}
}

void HttpMetaCache::SaveEventually()
{
	// reset the save timer
	saveBatchingTimer.stop();
	saveBatchingTimer.start(30000);
}

void HttpMetaCache::SaveNow()
{
	QJsonObject toplevel;
	toplevel.insert("version", QJsonValue(QString("1")));
	QJsonArray entriesArr;
	for (auto group : m_entries)
	{
		for (auto entry : group.entry_list)
		{
			// do not save stale entries. they are dead.
			if(entry->stale)
			{
				continue;
			}
			QJsonObject entryObj;
			entryObj.insert("base", QJsonValue(entry->base));
			entryObj.insert("path", QJsonValue(entry->path));
			entryObj.insert("md5sum", QJsonValue(entry->md5sum));
			entryObj.insert("etag", QJsonValue(entry->etag));
			entryObj.insert("last_changed_timestamp",
							QJsonValue(double(entry->local_changed_timestamp)));
			if (!entry->remote_changed_timestamp.isEmpty())
				entryObj.insert("remote_changed_timestamp",
								QJsonValue(entry->remote_changed_timestamp));
			entriesArr.append(entryObj);
		}
	}
	toplevel.insert("entries", entriesArr);

	QJsonDocument doc(toplevel);
	try
	{
		FS::write(m_index_file, doc.toJson());
	}
	catch (Exception & e)
	{
		qWarning() << e.what();
	}
}