swift
Loading...
Searching...
No Matches
databasereader.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2015 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <QByteArray>
7#include <QFileInfo>
8#include <QJsonDocument>
9#include <QJsonObject>
10#include <QJsonValueRef>
11#include <QMetaObject>
12#include <QNetworkReply>
13#include <QPointer>
14#include <QReadLocker>
15#include <QStringBuilder>
16#include <QUrl>
17#include <QWriteLocker>
18
19#include "core/application.h"
24#include "misc/directoryutils.h"
25#include "misc/logcategories.h"
26#include "misc/logmessage.h"
30#include "misc/verify.h"
31
32using namespace swift::misc;
33using namespace swift::misc::db;
34using namespace swift::misc::network;
35using namespace swift::core;
36using namespace swift::core::data;
37using namespace swift::core::db;
38
39namespace swift::core::db
40{
44
45 void CDatabaseReader::readInBackgroundThread(CEntityFlags::Entity entities, const QDateTime &newerThan)
46 {
47 if (!this->doWorkCheck())
48 {
49 return;
50 }
51 Q_ASSERT_X(hasStarted(), Q_FUNC_INFO, "Thread was not started yet!");
52
53 // we accept cached data
54 Q_ASSERT_X(!entities.testFlag(CEntityFlags::DbInfoObjectEntity), Q_FUNC_INFO, "Read info objects directly");
55 const bool hasDbInfoObjects =
56 this->hasDbInfoObjects(); // no info objects is not necessarily an error, but indicates a) either data not
57 // available (DB down) or b) only caches are used
58 // const bool hasSharedInfoObjects = this->hasSharedInfoObjects();
59 CEntityFlags::Entity allEntities = entities;
60 CEntityFlags::Entity cachedEntities = CEntityFlags::NoEntity;
61 CEntityFlags::Entity dbEntities = CEntityFlags::NoEntity;
62 CEntityFlags::Entity sharedEntities = CEntityFlags::NoEntity;
63 CEntityFlags::Entity currentEntity =
64 CEntityFlags::iterateDbEntities(allEntities); // CEntityFlags::InfoObjectEntity will be ignored
65 while (currentEntity)
66 {
67 const CDatabaseReaderConfig config(this->getConfigForEntity(currentEntity));
68 const QString currentEntityName = CEntityFlags::entitiesToString(currentEntity);
69
70 // retrieval mode
71 const CDbFlags::DataRetrievalMode rm = config.getRetrievalMode(); // DB reading, cache, shared
72 Q_ASSERT_X(!rm.testFlag(CDbFlags::Unspecified), Q_FUNC_INFO, "Missing retrieval mode");
73 const QString rmString = CDbFlags::flagToString(rm);
74 const CDbFlags::DataRetrievalModeFlag rmDbOrSharedFlag =
76 const QString rmDbOrSharedFlagString = CDbFlags::flagToString(rmDbOrSharedFlag);
77 const bool rmDbReadingOrShared =
78 (rmDbOrSharedFlag == CDbFlags::DbReading || rmDbOrSharedFlag == CDbFlags::Shared);
79 const int currentEntityCount = this->getCacheCount(currentEntity);
80
81 if (rm.testFlag(CDbFlags::Ignore) || rm.testFlag(CDbFlags::Canceled))
82 {
83 // do not load
84 }
85 else if (rm.testFlag(CDbFlags::Cached))
86 {
87 //
88 // !!! info object comparisons only for: cache + shared or cache + DB data
89 //
90 if (hasDbInfoObjects && rmDbReadingOrShared)
91 {
92 // check mode here for consistency
93 Q_ASSERT_X(!getBaseUrl(rmDbOrSharedFlag).isEmpty(), Q_FUNC_INFO, "Wrong retrieval mode");
94
95 CUrl oldUrlInfo;
96 CUrl newUrlInfo;
97 const bool changedUrl = this->hasChangedUrl(currentEntity, oldUrlInfo, newUrlInfo);
98 const QDateTime cacheTs(this->getCacheTimestamp(currentEntity));
99 const QDateTime latestEntityTs(this->getLatestEntityTimestampFromDbInfoObjects(currentEntity));
100 const qint64 cacheTimestamp = cacheTs.isValid() ? cacheTs.toMSecsSinceEpoch() : -1;
101 const qint64 latestEntityTimestamp =
102 latestEntityTs.isValid() ? latestEntityTs.toMSecsSinceEpoch() : -1;
103 Q_ASSERT_X(latestEntityTimestamp >= 0, Q_FUNC_INFO, "Missing timestamp");
104 if (!changedUrl && cacheTimestamp >= latestEntityTimestamp && cacheTimestamp >= 0 &&
105 latestEntityTimestamp >= 0)
106 {
107 this->admitCaches(currentEntity);
108 cachedEntities |= currentEntity; // read from cache
109 CLogMessage(this).info(u"Using cache for '%1' (%2, %3)")
110 << currentEntityName << cacheTs.toString() << cacheTimestamp;
111 }
112 else
113 {
114 Q_ASSERT_X(rmDbReadingOrShared, Q_FUNC_INFO, "Wrong retrieval mode");
115 if (rmDbOrSharedFlag == CDbFlags::DbReading)
116 {
117 dbEntities |= currentEntity;
118 }
119 else if (rmDbOrSharedFlag == CDbFlags::Shared)
120 {
121 sharedEntities |= currentEntity;
122 }
123
124 if (changedUrl)
125 {
126 CLogMessage(this).info(
127 u"Data location for '%1' changed ('%2'->'%3'), will override cache for reading '%4'")
128 << currentEntityName << oldUrlInfo.toQString() << newUrlInfo.toQString()
129 << rmDbOrSharedFlagString;
130 }
131 else
132 {
133 CLogMessage(this).info(u"Cache for '%1' outdated, latest entity (%2, %3), reading '%4'")
134 << currentEntityName << latestEntityTs.toString() << latestEntityTimestamp
135 << rmDbOrSharedFlagString;
136 }
137 }
138 }
139 else
140 {
141 if (!rmDbReadingOrShared)
142 {
143 CLogMessage(this).info(u"No DB or shared reading for '%1', read mode is: '%2'")
144 << currentEntityName << rmString;
145 }
146 if (!hasDbInfoObjects)
147 {
148 CLogMessage(this).info(u"No DB info objects for '%1', read mode is: '%2'")
149 << currentEntityName << rmString;
150 }
151 if (currentEntityCount > 0)
152 {
153 CLogMessage(this).info(u"Cache for '%1' already read, %2 entries")
154 << currentEntityName << currentEntityCount;
155 }
156 else
157 {
158 // no info objects, server down or no shared/db read mode
159 this->admitCaches(currentEntity);
160 if (!rmDbReadingOrShared)
161 {
162 // intentionally we do not want to read from DB/shared
163 CLogMessage(this).info(u"Triggered reading cache for '%1', read mode: %2")
164 << currentEntityName << rmString;
165 }
166 else
167 {
168 // we want to read from DB/shared, but have no info object
169 CLogMessage(this).info(u"No info object for '%1', triggered reading cache, read mode: %2")
170 << currentEntityName << rmString;
171 }
172 }
173 cachedEntities |= currentEntity; // read from cache
174 }
175 }
176 else
177 {
178 // cache ignored
179 Q_ASSERT_X(rmDbReadingOrShared, Q_FUNC_INFO, "Wrong retrieval mode");
180 if (rmDbOrSharedFlag == CDbFlags::DbReading)
181 {
182 dbEntities |= currentEntity;
183 }
184 else if (rmDbOrSharedFlag == CDbFlags::Shared)
185 {
186 sharedEntities |= currentEntity;
187 }
188 }
189 currentEntity = CEntityFlags::iterateDbEntities(allEntities);
190 }
191
192 // signals for the cached entities
193 if (cachedEntities != CEntityFlags::NoEntity)
194 {
195 this->emitReadSignalPerSingleCachedEntity(cachedEntities, true);
196 }
197
198 // Real read from DB
199 if (dbEntities != CEntityFlags::NoEntity)
200 {
201 CLogMessage(this).info(u"Start reading DB entities: %1") << CEntityFlags::entitiesToString(dbEntities);
203 }
204
205 // Real read from shared
206 if (sharedEntities != CEntityFlags::NoEntity)
207 {
208 CLogMessage(this).info(u"Start reading shared entities: %1")
209 << CEntityFlags::entitiesToString(sharedEntities);
210 this->startReadFromBackendInBackgroundThread(dbEntities, CDbFlags::Shared, newerThan);
211 }
212 }
213
214 CEntityFlags::Entity CDatabaseReader::triggerLoadingDirectlyFromDb(CEntityFlags::Entity entities,
215 const QDateTime &newerThan)
216 {
218 return entities;
219 }
220
221 CEntityFlags::Entity CDatabaseReader::triggerLoadingDirectlyFromSharedFiles(CEntityFlags::Entity entities,
222 bool checkCacheTsUpfront)
223 {
224 if (entities == CEntityFlags::NoEntity)
225 {
227 }
228 if (checkCacheTsUpfront)
229 {
230 CEntityFlags::Entity newerHeaderEntities = this->getEntitesWithNewerSharedInfoObject(entities);
231 if (newerHeaderEntities != entities)
232 {
233 const CEntityFlags::Entity validInCacheEntities = (entities ^ newerHeaderEntities) & entities;
234 CLogMessage(this).info(u"Reduced '%1' to '%2' before triggering load of shared files (still in cache)")
235 << CEntityFlags::entitiesToString(entities) << CEntityFlags::entitiesToString(newerHeaderEntities);
236
237 // In case we have difference entities we treat them as they were loaded, they result from still being
238 // in the cache Using timer to first finish this function, then the resulting signal
239 if (validInCacheEntities != CEntityFlags::NoEntity)
240 {
241 QPointer<CDatabaseReader> myself(this);
242 QTimer::singleShot(0, this, [=, this] {
243 if (!myself)
244 {
245 return;
246 }
247 if (!sApp || sApp->isShuttingDown())
248 {
249 return;
250 }
251 emit this->dataRead(validInCacheEntities, CEntityFlags::ReadFinished, 0, {});
252 });
253 }
254 if (newerHeaderEntities == CEntityFlags::NoEntity)
255 {
257 }
258 entities = newerHeaderEntities;
259 }
260 }
262 return entities;
263 }
264
267 const QDateTime &newerThan)
268 {
269 Q_ASSERT_X(mode == CDbFlags::DbReading || mode == CDbFlags::Shared, Q_FUNC_INFO, "Wrong mode");
270
271 // ps_read is implemented in the derived classes
272 if (entities == CEntityFlags::NoEntity)
273 {
274 return;
275 }
276
277 QPointer<CDatabaseReader> myself(this);
278 QTimer::singleShot(0, this, [=, this] {
279 if (!sApp || sApp->isShuttingDown() || !myself)
280 {
281 return;
282 }
283 this->read(entities, mode, newerThan);
284 });
285 }
286
289 {
290 Q_ASSERT_X(nwReply, Q_FUNC_INFO, "missing reply");
291 JsonDatastoreResponse datastoreResponse;
292 const bool ok = this->setHeaderInfoPart(datastoreResponse, nwReply);
293 if (ok)
294 {
295 const QString dataFileData = nwReply->readAll();
296 nwReply->close(); // close asap
297 datastoreResponse.setStringSize(dataFileData.size());
298 if (dataFileData.isEmpty())
299 {
300 datastoreResponse.setMessage(
301 CStatusMessage(this, CStatusMessage::SeverityError, u"Empty response, no data"));
302 }
303 else
304 {
305 CDatabaseReader::stringToDatastoreResponse(dataFileData, datastoreResponse);
306 }
307 }
308 return datastoreResponse;
309 }
310
312 {
313 HeaderResponse headerResponse;
314 const bool success = this->setHeaderInfoPart(headerResponse, nwReply);
315 Q_UNUSED(success);
316 return headerResponse;
317 }
318
320 QNetworkReply *nwReply) const
321 {
322 Q_ASSERT_X(nwReply, Q_FUNC_INFO, "Missing reply");
323 this->threadAssertCheck();
324 if (!this->doWorkCheck())
325 {
326 nwReply->abort();
327 headerResponse.setMessage(
328 CStatusMessage(this, CStatusMessage::SeverityError, u"Terminated data parsing process"));
329 return false; // stop, terminate straight away, ending thread
330 }
331
332 headerResponse.setValues(nwReply);
333 if (nwReply->error() == QNetworkReply::NoError)
334 {
335 // do not close because of obtaining data
336 return true;
337 }
338 else
339 {
340 // no valid response
341 const QString error(nwReply->errorString());
342 const QString url(nwReply->url().toString());
343 nwReply->abort();
344 headerResponse.setMessage(
345 CStatusMessage(this, CStatusMessage::SeverityError, u"Reading data failed: '" % error % u"' " % url));
346 return false;
347 }
348 }
349
352 {
353 this->setReplyStatus(nwReply);
355 if (dsr.isSharedFile())
356 {
358 }
359 else
360 {
361 if (dsr.isLoadedFromDb())
362 {
363 const bool s = !dsr.hasErrorMessage();
364 emit this->swiftDbDataRead(s);
365 }
366 }
367 return dsr;
368 }
369
371 {
372 static const CDbInfoList e;
373 if (!sApp->hasWebDataServices())
374 {
375 return e;
376 }
377 if (!sApp->getWebDataServices()->getDbInfoDataReader())
378 {
379 return e;
380 }
381 return sApp->getWebDataServices()->getDbInfoDataReader()->getInfoObjects();
382 }
383
385 {
386 static const CDbInfoList e;
387 if (!sApp->hasWebDataServices())
388 {
389 return e;
390 }
391 if (!sApp->getWebDataServices()->getSharedInfoDataReader())
392 {
393 return e;
394 }
395 return sApp->getWebDataServices()->getSharedInfoDataReader()->getInfoObjects();
396 }
397
399
401
402 bool CDatabaseReader::hasSharedFileHeader(const CEntityFlags::Entity entity) const
403 {
404 Q_ASSERT_X(CEntityFlags::isSingleEntity(entity), Q_FUNC_INFO, "need single entity");
405 return m_sharedFileResponses.contains(entity);
406 }
407
408 bool CDatabaseReader::hasSharedFileHeaders(const CEntityFlags::Entity entities) const
409 {
410 CEntityFlags::Entity myEntities = maskBySupportedEntities(entities);
411 CEntityFlags::Entity currentEntity = CEntityFlags::iterateDbEntities(myEntities);
412 while (currentEntity != CEntityFlags::NoEntity)
413 {
414 if (!hasSharedFileHeader(currentEntity))
415 {
416 return false;
417 }
418 currentEntity = CEntityFlags::iterateDbEntities(myEntities);
419 }
420 return true;
421 }
422
424 {
425 Q_ASSERT_X(CEntityFlags::isSingleEntity(entity), Q_FUNC_INFO, "need single entity");
426 static const QDateTime e;
427 const CDbInfoList il(getDbInfoObjects());
428 if (il.isEmpty() || entity == CEntityFlags::NoEntity)
429 {
430 return e;
431 }
432
433 // for some entities there can be more than one entry because of the
434 // raw tables (see DB view last updates)
435 const CDbInfo info = il.findFirstByEntityOrDefault(entity);
436 if (!info.isValid())
437 {
438 return e;
439 }
440 return info.getUtcTimestamp();
441 }
442
444 {
445 Q_ASSERT_X(CEntityFlags::isSingleEntity(entity), Q_FUNC_INFO, "need single entity");
446 static const QDateTime e;
447 const CDbInfoList il(this->getSharedInfoObjects());
448 if (il.isEmpty() || entity == CEntityFlags::NoEntity)
449 {
450 return e;
451 }
452
453 const CDbInfo info = il.findFirstByEntityOrDefault(entity);
454 if (!info.isValid())
455 {
456 return e;
457 }
458 return info.getUtcTimestamp();
459 }
460
462 {
463 Q_ASSERT_X(CEntityFlags::isSingleEntity(entity), Q_FUNC_INFO, "need single entity");
464 static const QDateTime e;
465 if (!this->hasSharedFileHeader(entity))
466 {
467 return e;
468 }
469 return m_sharedFileResponses[entity].getLastModifiedTimestamp();
470 }
471 bool CDatabaseReader::isSharedHeaderNewerThanCacheTimestamp(CEntityFlags::Entity entity) const
472 {
473 Q_ASSERT_X(CEntityFlags::isSingleEntity(entity), Q_FUNC_INFO, "need single entity");
474 const QDateTime cacheTs(this->getCacheTimestamp(entity));
475 if (!cacheTs.isValid())
476 {
477 return true;
478 } // we have no cache ts
479
480 const QDateTime headerTimestamp(this->getLatestSharedFileHeaderTimestamp(entity));
481 if (!headerTimestamp.isValid())
482 {
483 return false;
484 }
485 return headerTimestamp > cacheTs;
486 }
487
489 {
490 Q_ASSERT_X(CEntityFlags::isSingleEntity(entity), Q_FUNC_INFO, "need single entity");
491 const QDateTime cacheTs(this->getCacheTimestamp(entity));
492 if (!cacheTs.isValid())
493 {
494 return true;
495 } // we have no cache ts
496
497 const QDateTime sharedInfoTimestamp(this->getLatestEntityTimestampFromSharedInfoObjects(entity));
498 if (!sharedInfoTimestamp.isValid())
499 {
500 return false;
501 }
502 return sharedInfoTimestamp > cacheTs;
503 }
504
505 CEntityFlags::Entity CDatabaseReader::getEntitesWithNewerHeaderTimestamp(CEntityFlags::Entity entities) const
506 {
508 CEntityFlags::Entity currentEntity = CEntityFlags::iterateDbEntities(entities);
509 CEntityFlags::Entity newerEntities = CEntityFlags::NoEntity;
510 while (currentEntity != CEntityFlags::NoEntity)
511 {
512 if (this->isSharedHeaderNewerThanCacheTimestamp(currentEntity))
513 {
514 newerEntities |= currentEntity;
515 }
516 currentEntity = CEntityFlags::iterateDbEntities(entities);
517 }
518 return newerEntities;
519 }
520
521 CEntityFlags::Entity CDatabaseReader::getEntitesWithNewerSharedInfoObject(CEntityFlags::Entity entities) const
522 {
524 CEntityFlags::Entity currentEntity = CEntityFlags::iterateDbEntities(entities);
525 CEntityFlags::Entity newerEntities = CEntityFlags::NoEntity;
526 while (currentEntity != CEntityFlags::NoEntity)
527 {
528 if (this->isSharedInfoObjectNewerThanCacheTimestamp(currentEntity))
529 {
530 newerEntities |= currentEntity;
531 }
532 currentEntity = CEntityFlags::iterateDbEntities(entities);
533 }
534 return newerEntities;
535 }
536
538 {
539 return m_config.findFirstOrDefaultForEntity(entity);
540 }
541
542 CEntityFlags::Entity CDatabaseReader::emitReadSignalPerSingleCachedEntity(CEntityFlags::Entity cachedEntities,
543 bool onlyIfHasData)
544 {
545 if (cachedEntities == CEntityFlags::NoEntity)
546 {
548 }
549 CEntityFlags::Entity emitted = CEntityFlags::NoEntity;
550 CEntityFlags::Entity cachedEntitiesToEmit = cachedEntities;
551 CEntityFlags::Entity currentCachedEntity = CEntityFlags::iterateDbEntities(cachedEntitiesToEmit);
552 while (currentCachedEntity)
553 {
554 const int c = this->getCacheCount(currentCachedEntity);
555 if (!onlyIfHasData || c > 0)
556 {
557 emit this->dataRead(currentCachedEntity, CEntityFlags::ReadFinished, c, {});
558 emitted |= currentCachedEntity;
559 }
560 currentCachedEntity = CEntityFlags::iterateDbEntities(cachedEntitiesToEmit);
561 }
562 return emitted;
563 }
564
565 void CDatabaseReader::emitAndLogDataRead(CEntityFlags::Entity entity, int number, const JsonDatastoreResponse &res)
566 {
567 // never emit when lock is held, deadlock
568 Q_ASSERT_X(CEntityFlags::isSingleEntity(entity), Q_FUNC_INFO, "Expect single entity");
569 CLogMessage(this).info(u"Read %1 entities of '%2' from '%3' (%4)")
570 << number << CEntityFlags::entitiesToString(entity) << res.getUrlString()
572 emit this->dataRead(entity,
574 number, res.getUrl());
575 }
576
577 void CDatabaseReader::logNoWorkingUrl(CEntityFlags::Entity entity)
578 {
579 const CStatusMessage msg = CStatusMessage(this, m_severityNoWorkingUrl, u"No working URL for '%1'")
582 }
583
585 {
586 if (!sApp || sApp->isShuttingDown())
587 {
588 return {};
589 }
590 switch (mode)
591 {
592 case CDbFlags::DbReading: return this->getDbServiceBaseUrl().withAppendedPath("/service");
594 case CDbFlags::Shared: return sApp->getGlobalSetup().getSharedDbDataDirectoryUrl();
595 default: qFatal("Wrong mode"); break;
596 }
597 return {};
598 }
599
600 bool CDatabaseReader::isChangedUrl(const CUrl &oldUrl, const CUrl &currentUrl)
601 {
602 if (oldUrl.isEmpty())
603 {
604 return true;
605 }
606 Q_ASSERT_X(!currentUrl.isEmpty(), Q_FUNC_INFO, "No base URL");
607
608 const QString old(oldUrl.getFullUrl(false));
609 const QString current(currentUrl.getFullUrl(false));
610 return old != current;
611 }
612
614 {
615 // wrap pointer, make sure any exit cleans up reply
616 // required to use delete later as object is created in a different thread
618 if (!this->doWorkCheck())
619 {
620 return;
621 }
622 this->receivedSharedFileHeaderNonClosing(nwReplyPtr);
623 nwReply->close();
624 }
625
627 {
628 if (this->isAbandoned())
629 {
630 return;
631 }
632
633 const HeaderResponse headerResponse = this->transformReplyIntoHeaderResponse(nwReplyPtr);
634 const QString fileName = nwReplyPtr->url().fileName();
635 const CEntityFlags::Entity entity = CEntityFlags::singleEntityByName(fileName);
636 m_sharedFileResponses[entity] = headerResponse;
637
638 CLogMessage(this).info(u"Received header for shared file of '%1' from '%2'")
639 << fileName << headerResponse.getUrl().toQString();
640 emit this->sharedFileHeaderRead(entity, fileName, !headerResponse.hasWarningOrAboveMessage());
641 }
642
648
655
661
666
667 CEntityFlags::Entity CDatabaseReader::maskBySupportedEntities(CEntityFlags::Entity entities) const
668 {
669 return entities & this->getSupportedEntities();
670 }
671
672 bool CDatabaseReader::supportsAnyOfEntities(CEntityFlags::Entity entities) const
673 {
674 return static_cast<int>(this->maskBySupportedEntities(entities)) > 0;
675 }
676
677 bool CDatabaseReader::hasCacheTimestampNewerThan(CEntityFlags::Entity entity, const QDateTime &threshold) const
678 {
679 const QDateTime ts = this->getCacheTimestamp(entity);
680 if (!ts.isValid())
681 {
682 return false;
683 }
684 return ts > threshold;
685 }
686
688
690 {
691 return this->initFromLocalResourceFiles(this->getSupportedEntities(), inBackground);
692 }
693
695 CStatusMessageList CDatabaseReader::initFromLocalResourceFiles(CEntityFlags::Entity entities, bool inBackground)
696 {
697 const bool overrideNewerOnly = true;
698 entities = this->maskBySupportedEntities(entities);
699
700 if (inBackground || !CThreadUtils::isInThisThread(this))
701 {
703 overrideNewerOnly);
704 return s ? CStatusMessage(this).info(u"Started reading in background from '%1' of entities: '%2'")
706 CStatusMessage(this).error(u"Starting reading in background from '%1' of entities: '%2' failed")
707 << CSwiftDirectories::staticDbFilesDirectory() << CEntityFlags::entitiesToString(entities);
708 }
709 else
710 {
711 return this->readFromJsonFiles(CSwiftDirectories::staticDbFilesDirectory(), entities, overrideNewerOnly);
712 }
713 }
715
717 {
719 m_statusMessage = message;
720 m_1stReplyStatus = status;
721 m_1stReplyReceived = true;
722 }
723
725 {
726 Q_ASSERT_X(nwReply, Q_FUNC_INFO, "Missing network reply");
727 if (nwReply && nwReply->isFinished())
728 {
729 this->logNetworkReplyReceived(nwReply);
730 this->setReplyStatus(nwReply->error(), nwReply->errorString());
731 }
732 }
733
734 bool CDatabaseReader::overrideCacheFromFile(bool overrideNewerOnly, const QFileInfo &fileInfo,
735 CEntityFlags::Entity entity, CStatusMessageList &msgs) const
736 {
737 if (!fileInfo.birthTime().isValid())
738 {
739 return false;
740 }
741 if (!overrideNewerOnly)
742 {
743 return true;
744 }
745
746 const qint64 fileTs = fileInfo.birthTime().toUTC().toMSecsSinceEpoch();
747 const QDateTime cacheDateTime(this->getCacheTimestamp(entity));
748 if (!cacheDateTime.isValid())
749 {
750 return true;
751 } // no cache
752 const qint64 cacheTs = cacheDateTime.toUTC().toMSecsSinceEpoch();
753 if (fileTs > cacheTs)
754 {
755 msgs.push_back(CStatusMessage(this).info(u"File '%1' is newer than cache (%2)")
756 << fileInfo.absoluteFilePath() << cacheDateTime.toUTC().toString());
757 return true;
758 }
759 else
760 {
761 msgs.push_back(CStatusMessage(this).info(u"File '%1' is not newer than cache (%2)")
762 << fileInfo.absoluteFilePath() << cacheDateTime.toUTC().toString());
763 return false;
764 }
765 }
766
767 void CDatabaseReader::logParseMessage(const QString &entity, int size, int msElapsed,
768 const CDatabaseReader::JsonDatastoreResponse &response) const
769 {
770 CLogMessage(this).info(u"Parsed %1 %2 in %3ms, thread %4 | '%5'")
771 << size << entity << msElapsed << CThreadUtils::currentThreadInfo() << response.toQString();
772 }
773
774 void CDatabaseReader::networkReplyProgress(int logId, qint64 current, qint64 max, const QUrl &url)
775 {
776 CThreadedReader::networkReplyProgress(logId, current, max, url);
777 const QString fileName = url.fileName();
778 const CEntityFlags::Entity entity = CEntityFlags::singleEntityByName(fileName);
780 {
782 m_networkReplyMax, url);
783 }
784 }
785
787 {
788 Q_ASSERT_X(CEntityFlags::isSingleEntity(entity), Q_FUNC_INFO, "needs single entity");
789 switch (mode)
790 {
793 default:
795 }
796 }
797
799 {
800 if (!ts.isValid())
801 {
802 return {};
803 }
804 return ts.toUTC().toString(Qt::ISODate);
805 }
806
814
816 {
817 static const QString p("latestTimestamp");
818 return p;
819 }
820
822 {
823 if (!ts.isValid()) return {};
825 return q;
826 }
827
829 {
830 static const CUrl dbUrl(sApp->getGlobalSetup().getDbRootDirectoryUrl());
831 return dbUrl;
832 }
833
834 void CDatabaseReader::cacheHasChanged(CEntityFlags::Entity entities)
835 {
836 this->emitReadSignalPerSingleCachedEntity(entities, false);
837 }
838
839 void CDatabaseReader::stringToDatastoreResponse(const QString &jsonContent,
840 JsonDatastoreResponse &datastoreResponse)
841 {
842 const int status = datastoreResponse.getHttpStatusCode();
843 if (jsonContent.isEmpty())
844 {
845 static const QString errorMsg = "Empty JSON string, status: %1, URL: '%2', load time: %3";
846 datastoreResponse.setMessage(
848 errorMsg.arg(status).arg(datastoreResponse.getUrlString(),
849 datastoreResponse.getLoadTimeStringWithStartedHint())));
850 return;
851 }
852
853 const QJsonDocument jsonResponse = CDatabaseUtils::databaseJsonToQJsonDocument(jsonContent);
854 if (jsonResponse.isEmpty())
855 {
857 {
858 static const QString errorMsg = "Looks like PHP errror, status %1, URL: '%2', msg: %3";
859 const QString phpErrorMessage = CNetworkUtils::removeHtmlPartsFromPhpErrorMessage(jsonContent);
860 datastoreResponse.setMessage(
862 errorMsg.arg(status).arg(datastoreResponse.getUrlString(), phpErrorMessage)));
863 }
864 else
865 {
866 static const QString errorMsg = "Empty JSON document, URL: '%1', load time: %2";
867 datastoreResponse.setMessage(
869 errorMsg.arg(datastoreResponse.getUrlString(),
870 datastoreResponse.getLoadTimeStringWithStartedHint())));
871 }
872 return;
873 }
874
875 if (jsonResponse.isArray())
876 {
877 // directly an array, no further info
878 datastoreResponse.setJsonArray(jsonResponse.array());
879 datastoreResponse.setLastModifiedTimestamp(QDateTime::currentDateTimeUtc());
880 }
881 else
882 {
883 const QJsonObject responseObject(jsonResponse.object());
884 datastoreResponse.setJsonArray(responseObject["data"].toArray());
885 const QString ts(responseObject["latest"].toString());
886 datastoreResponse.setLastModifiedTimestamp(ts.isEmpty() ? QDateTime::currentDateTimeUtc() :
888 datastoreResponse.setRestricted(responseObject["restricted"].toBool());
889 }
890 }
891
893 {
894 return this->getUrl().getHost() == getDbUrl().getHost();
895 }
896
898 {
899 m_jsonArray = value;
900 m_arraySize = value.size();
901 }
902
904 {
905 static const QString s("DB: %1 | restricted: %2 | array: %3 | string size: %4 | content: %5");
906 return s.arg(boolToYesNo(this->isLoadedFromDb()), boolToYesNo(this->isRestricted()))
907 .arg(this->getArraySize())
908 .arg(m_stringSize)
909 .arg(this->getContentLengthHeader());
910 }
911
913 {
914 const QString fn(getUrl().getFileName());
916 }
917
919 {
920 return QStringLiteral("%1ms").arg(getLoadTimeMs());
921 }
922
924 {
925 if (m_requestStarted < 0)
926 {
927 return this->getLoadTimeString();
928 }
929 const qint64 diff = QDateTime::currentMSecsSinceEpoch() - m_requestStarted;
930 static const QString s("%1 load time, started %2ms before now");
931 return s.arg(this->getLoadTimeString()).arg(diff);
932 }
933
935 {
936 Q_ASSERT_X(nwReply, Q_FUNC_INFO, "Need valid reply");
937 this->setUrl(nwReply->url());
938 const QVariant started = nwReply->property("started");
939 if (started.isValid() && started.canConvert<qint64>())
940 {
941 const qint64 now = QDateTime::currentMSecsSinceEpoch();
942 const auto start = started.value<qint64>();
943 this->setLoadTimeMs(now - start);
944 m_requestStarted = start;
945 m_responseReceived = now;
946 }
947
948 const QVariant qvStatusCode = nwReply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
949 if (qvStatusCode.isValid() && qvStatusCode.canConvert<int>())
950 {
951 m_httpStatusCode = qvStatusCode.toInt();
952 }
953
954 const QDateTime lastModified = nwReply->header(QNetworkRequest::LastModifiedHeader).toDateTime();
955 const qulonglong size = nwReply->header(QNetworkRequest::ContentLengthHeader).toULongLong();
956 this->setLastModifiedTimestamp(lastModified);
957 this->setContentLengthHeader(size);
958 }
959} // namespace swift::core::db
std::atomic_llong m_networkReplyCurrent
current bytes
static const QStringList & getLogCategories()
Log categories.
virtual void networkReplyProgress(int logId, qint64 current, qint64 max, const QUrl &url)
Network request progress.
std::atomic_int m_networkReplyProgress
Progress percentage 0...100.
void threadAssertCheck() const
Make sure everything runs correctly in own thread.
void logNetworkReplyReceived(QNetworkReply *reply)
Network reply received, mark in m_urlReadLog.
CThreadedReader(const CThreadedReader &)=delete
Copy constructor.
bool doWorkCheck() const
Still enabled etc.?
std::atomic_llong m_networkReplyMax
max bytes
Details how to read a certain entity.
Value object encapsulating a list of reader configs.
Specialized version of threaded reader for DB data.
virtual QDateTime getCacheTimestamp(swift::misc::network::CEntityFlags::Entity entity) const =0
Get cache timestamp.
virtual bool hasChangedUrl(swift::misc::network::CEntityFlags::Entity entity, swift::misc::network::CUrl &oldUrlInfo, swift::misc::network::CUrl &newUrlInfo) const =0
Changed URL, means the cache values have been read from elsewhere.
virtual void admitCaches(swift::misc::network::CEntityFlags::Entity entities)=0
Admit caches for given entities.
QDateTime getLatestSharedFileHeaderTimestamp(swift::misc::network::CEntityFlags::Entity entity) const
Header timestamp (last-modified) for shared file.
void emitAndLogDataRead(swift::misc::network::CEntityFlags::Entity entity, int number, const JsonDatastoreResponse &res)
Emit signal and log when data have been read.
swift::misc::CStatusMessageList initFromLocalResourceFiles(bool inBackground)
Init from local resource file.
swift::misc::network::CEntityFlags::Entity emitReadSignalPerSingleCachedEntity(swift::misc::network::CEntityFlags::Entity cachedEntities, bool onlyIfHasData)
Split into single entity and send dataRead signal.
HeaderResponse transformReplyIntoHeaderResponse(QNetworkReply *nwReply) const
Check if terminated or error, otherwise set header information.
static QString queryLatestTimestamp(const QDateTime &ts)
Latest timestamp query for DB.
QNetworkReply::NetworkError m_1stReplyStatus
Successful connection?
bool isSharedHeaderNewerThanCacheTimestamp(swift::misc::network::CEntityFlags::Entity entity) const
Is the file timestamp newer than cache timestamp?
swift::misc::db::CDbInfoList getSharedInfoObjects() const
Shared info list (latest data timestamps from DB web service).
virtual void cacheHasChanged(swift::misc::network::CEntityFlags::Entity entities)
Cache for given entity has changed.
void networkReplyProgress(int logId, qint64 current, qint64 max, const QUrl &url)
Network request progress.
bool hasSharedInfoObjects() const
Shared info objects available?
swift::misc::CStatusMessage::StatusSeverity m_severityNoWorkingUrl
severity of message if there is no working URL
void sharedFileHeaderRead(swift::misc::network::CEntityFlags::Entity entity, const QString &fileName, bool success)
Header of shared file read.
bool hasReceivedOkReply() const
Has received Ok response from server at least once?
static QString dateTimeToDbLatestTs(const QDateTime &ts)
A newer than value understood by swift DB.
void setReplyStatus(QNetworkReply::NetworkError status, const QString &message="")
Feedback about connection status.
static const QStringList & getLogCategories()
Log categories.
virtual int getCacheCount(swift::misc::network::CEntityFlags::Entity entity) const =0
Cache`s number of entities.
void entityDownloadProgress(swift::misc::network::CEntityFlags::Entity entity, int logId, int progress, qint64 current, qint64 max, const QUrl &url)
Download progress for an entity.
QDateTime getLatestEntityTimestampFromSharedInfoObjects(swift::misc::network::CEntityFlags::Entity entity) const
Obtain latest object timestamp from shared info objects.
JsonDatastoreResponse transformReplyIntoDatastoreResponse(QNetworkReply *nwReply) const
Check if terminated or error, otherwise split into array of objects.
bool hasSharedFileHeader(const swift::misc::network::CEntityFlags::Entity entity) const
Header of shared file read (for single entity)?
QDateTime getLatestEntityTimestampFromDbInfoObjects(swift::misc::network::CEntityFlags::Entity entity) const
Obtain latest object timestamp from DB info objects.
void logNoWorkingUrl(swift::misc::network::CEntityFlags::Entity entity)
Log if no working URL exists, using m_noWorkingUrlSeverity.
bool supportsAnyOfEntities(swift::misc::network::CEntityFlags::Entity entities) const
Is any of the given entities supported here by this reader.
QString getSupportedEntitiesAsString() const
Supported entities as string.
void swiftDbDataRead(bool success)
DB have been read.
bool hasDbInfoObjects() const
DB info objects available?
swift::misc::network::CEntityFlags::Entity getEntitesWithNewerHeaderTimestamp(swift::misc::network::CEntityFlags::Entity entities) const
Those entities where the timestamp of the header is newer than the cache timestamp.
swift::misc::network::CEntityFlags::Entity getEntitesWithNewerSharedInfoObject(swift::misc::network::CEntityFlags::Entity entities) const
Those entities where the timestamp of a shared info object is newer than the cache timestamp.
CDatabaseReaderConfig getConfigForEntity(swift::misc::network::CEntityFlags::Entity entity) const
Config for given entity.
QMap< swift::misc::network::CEntityFlags::Entity, HeaderResponse > m_sharedFileResponses
file responses of the shared files
void receivedSharedFileHeader(QNetworkReply *nwReplyPtr)
Received a reply of a header for a shared file.
CDatabaseReader(QObject *owner, const CDatabaseReaderConfigList &config, const QString &name)
Constructor.
swift::misc::network::CEntityFlags::Entity maskBySupportedEntities(swift::misc::network::CEntityFlags::Entity entities) const
Mask by supported entities.
swift::misc::network::CEntityFlags::Entity triggerLoadingDirectlyFromSharedFiles(swift::misc::network::CEntityFlags::Entity entities, bool checkCacheTsUpfront)
Start loading from shared files in own thread.
bool hasSharedFileHeaders(const swift::misc::network::CEntityFlags::Entity entities) const
Headers of shared file read (for single entity)?
bool hasReceivedFirstReply() const
Has received 1st reply?
bool overrideCacheFromFile(bool overrideNewerOnly, const QFileInfo &fileInfo, swift::misc::network::CEntityFlags::Entity entity, swift::misc::CStatusMessageList &msgs) const
Override cache from file.
virtual swift::misc::network::CUrl getDbServiceBaseUrl() const =0
Get the service URL, individual for each reader.
static const QString & parameterLatestTimestamp()
Name of latest timestamp.
static const swift::misc::network::CUrl & getDbUrl()
DB base URL.
swift::misc::db::CDbInfoList getDbInfoObjects() const
DB Info list (latest data timestamps from DB web service).
virtual void read(swift::misc::network::CEntityFlags::Entity entities, swift::misc::db::CDbFlags::DataRetrievalModeFlag mode, const QDateTime &newerThan)=0
Read / re-read data file.
QString m_statusMessage
Returned status message from watchdog.
void startReadFromBackendInBackgroundThread(swift::misc::network::CEntityFlags::Entity entities, swift::misc::db::CDbFlags::DataRetrievalModeFlag mode, const QDateTime &newerThan=QDateTime())
Start reading in own thread (without config/caching).
virtual bool readFromJsonFilesInBackground(const QString &dir, swift::misc::network::CEntityFlags::Entity whatToRead, bool overrideNewer)=0
Data read from local data.
virtual swift::misc::network::CEntityFlags::Entity getSupportedEntities() const =0
Supported entities by this reader.
swift::misc::network::CUrl getBaseUrl(swift::misc::db::CDbFlags::DataRetrievalModeFlag mode) const
Base URL for mode (either a shared or DB URL).
void dataRead(swift::misc::network::CEntityFlags::Entity entities, swift::misc::network::CEntityFlags::ReadState state, int number, const QUrl &url)
Combined read signal.
virtual swift::misc::CStatusMessageList readFromJsonFiles(const QString &dir, swift::misc::network::CEntityFlags::Entity whatToRead, bool overrideNewer)=0
Data read from local data.
CDatabaseReaderConfigList m_config
DB reder configuration.
bool setHeaderInfoPart(HeaderResponse &headerResponse, QNetworkReply *nwReply) const
Set the header part.
static bool isChangedUrl(const swift::misc::network::CUrl &oldUrl, const swift::misc::network::CUrl &currentUrl)
Has URL been changed? Means we load from a different server.
static QString fileNameForMode(swift::misc::network::CEntityFlags::Entity entity, swift::misc::db::CDbFlags::DataRetrievalModeFlag mode)
File name for given mode, either php service or shared file name.
CDatabaseReader::JsonDatastoreResponse setStatusAndTransformReplyIntoDatastoreResponse(QNetworkReply *nwReply)
Check if terminated or error, otherwise split into array of objects.
void readInBackgroundThread(swift::misc::network::CEntityFlags::Entity entities, const QDateTime &newerThan)
Start reading in own thread.
bool m_1stReplyReceived
Successful connection?
swift::misc::network::CEntityFlags::Entity triggerLoadingDirectlyFromDb(swift::misc::network::CEntityFlags::Entity entities, const QDateTime &newerThan)
Start loading from DB in own thread.
const QString & getStatusMessage() const
Status message (error message).
void logParseMessage(const QString &entity, int size, int msElapsed, const JsonDatastoreResponse &response) const
Parsing info message.
bool isSharedInfoObjectNewerThanCacheTimestamp(swift::misc::network::CEntityFlags::Entity entity) const
Is the shared info timestamp newer than cache timestamp?
bool hasCacheTimestampNewerThan(swift::misc::network::CEntityFlags::Entity entity, const QDateTime &threshold) const
Has entity a valid and newer timestamp.
void receivedSharedFileHeaderNonClosing(QNetworkReply *nwReplyPtr)
Received a reply of a header for a shared file.
static QJsonDocument databaseJsonToQJsonDocument(const QString &content)
Database JSON from content string, which can be compressed.
const QObject * owner() const
Owner of the worker.
Definition worker.h:352
void start(QThread::Priority priority=QThread::InheritPriority)
Starts a thread and moves the worker into it.
Definition worker.cpp:174
static const QString & swiftDbWebservice()
Webservice with swift DB.
static const QString & webservice()
Webservice.
Class for emitting a log message.
Definition logmessage.h:27
static void preformatted(const CStatusMessage &statusMessage)
Sends a verbatim, preformatted message to the log.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
void push_back(const T &value)
Appends an element at the end of the sequence.
Definition sequence.h:308
bool isEmpty() const
Synonym for empty.
Definition sequence.h:285
Streamable status message, e.g.
static constexpr auto SeverityError
Status severities.
Status messages, e.g. from Core -> GUI.
Locations of important directories for swift files.
static const QString & staticDbFilesDirectory()
Where static DB files are located.
static QString currentThreadInfo()
Info about current thread, for debug messages.
static bool isInThisThread(const QObject *toBeTested)
Is the current thread the object's thread?
bool isAbandoned() const
For the task to check whether it can finish early.
Definition worker.cpp:162
bool hasStarted() const
True if the worker has started.
Definition worker.h:200
QDateTime getUtcTimestamp() const
Get timestamp.
static QDateTime parseTimestamp(const QString &timestamp)
Parse a timestamp object.
DataRetrievalModeFlag
Which data to read, requires corresponding readers.
Definition dbflags.h:25
@ DbReadingOrShared
read from DB or shared
Definition dbflags.h:37
@ Canceled
canceled DB reading
Definition dbflags.h:32
@ Unspecified
Unspecified.
Definition dbflags.h:26
@ DbReading
directly from DB
Definition dbflags.h:27
@ Shared
shared directory
Definition dbflags.h:29
@ Ignore
ignore this entity
Definition dbflags.h:33
@ SharedInfoOnly
shared info file only
Definition dbflags.h:30
static DataRetrievalModeFlag modeToModeFlag(DataRetrievalMode mode)
Mode to flag.
Definition dbflags.cpp:49
static QString flagToString(DataRetrievalModeFlag flag)
Convert to string.
Definition dbflags.cpp:18
Info about the latest models.
Definition dbinfo.h:22
static const QString & sharedInfoFileName()
Get shared info file name.
Definition dbinfo.cpp:155
static const QStringList & sharedFileNames()
The shared file names.
Definition dbinfo.cpp:147
bool isValid() const
Valid?
Definition dbinfo.cpp:23
static const QString & entityToSharedName(network::CEntityFlags::Entity entity)
Get shared file name.
Definition dbinfo.cpp:169
static const QString & entityToServiceName(network::CEntityFlags::Entity entity)
Get service file name.
Definition dbinfo.cpp:187
Value object encapsulating a list of info objects.
Definition dbinfolist.h:27
CDbInfo findFirstByEntityOrDefault(swift::misc::network::CEntityFlags::Entity entity) const
Find by entity.
QString toQString(bool i18n=false) const
Cast as QString.
Definition mixinstring.h:74
What and state of reading from web services.
Definition entityflags.h:22
static bool isSingleEntity(CEntityFlags::Entity flag)
Representing single entity?
static Entity singleEntityByName(const QString &name)
Get by name.
@ AllDbEntitiesNoInfoObjects
all DB entities, no info objects
Definition entityflags.h:48
@ DbInfoObjectEntity
info about DB data (kind of metadata)
Definition entityflags.h:28
@ ReadFinishedRestricted
finished a timestamp restricted read
Definition entityflags.h:65
static Entity iterateDbEntities(Entity &entities)
Return single entity and remove it from entities.
static QString entitiesToString(CEntityFlags::Entity entities, const QString &separator=", ")
Entities to string list.
static bool looksLikePhpErrorMessage(const QString &errorMessage)
Looks like PHP error messages.
static QString removeHtmlPartsFromPhpErrorMessage(const QString &errorMessage)
Remove the HTML formatting from a PHP error message.
Value object encapsulating information of a location, kind of simplified CValueObject compliant versi...
Definition url.h:27
const QString & getHost() const
Get host.
Definition url.h:55
bool isEmpty() const
Empty.
Definition url.cpp:63
CUrl withAppendedPath(const QString &path) const
Append path.
Definition url.cpp:151
QString getFullUrl(bool withQuery=true) const
Qualified name.
Definition url.cpp:102
Core data traits (aka cached values) and classes.
Classes interacting with the swift database (aka "datastore").
Backend services of the swift project, like dealing with the network or the simulators.
Definition actionbind.cpp:7
Free functions in swift::misc.
SWIFT_MISC_EXPORT const QString & boolToYesNo(bool v)
Bool to yes/no.
QDateTime currentDateTimeUtc()
qint64 currentMSecsSinceEpoch()
bool isValid() const const
qint64 toMSecsSinceEpoch() const const
QString toString(QStringView format) const const
QDateTime toUTC() const const
QString absoluteFilePath() const const
QDateTime birthTime() const const
QString errorString() const const
QByteArray readAll()
qsizetype size() const const
QJsonArray array() const const
bool isArray() const const
bool isEmpty() const const
QJsonObject object() const const
virtual void abort()=0
QVariant attribute(QNetworkRequest::Attribute code) const const
virtual void close() override
QNetworkReply::NetworkError error() const const
QVariant header(QNetworkRequest::KnownHeaders header) const const
bool isFinished() const const
QUrl url() const const
QObject(QObject *parent)
QVariant property(const char *name) const const
QString arg(Args &&... args) const const
bool isEmpty() const const
qsizetype size() const const
bool contains(QLatin1StringView str, Qt::CaseSensitivity cs) const const
CaseInsensitive
char * toString(QSizePolicy sp)
QString fileName(QUrl::ComponentFormattingOptions options) const const
QString toString(QUrl::FormattingOptions options) const const
bool canConvert() const const
bool isValid() const const
QDateTime toDateTime() const const
int toInt(bool *ok) const const
qulonglong toULongLong(bool *ok) const const
T value() const &const
QString getUrlString() const
URL loaded as string.
const swift::misc::network::CUrl & getUrl() const
URL loaded.
void setLoadTimeMs(qint64 deltaTime)
Set the load time (delta start -> response received).
void setValues(const QNetworkReply *nwReply)
Set reply values.
void setUrl(const swift::misc::network::CUrl &url)
Set the loaded URL.
bool hasWarningOrAboveMessage() const
Warning or error message?
void setLastModifiedTimestamp(const QDateTime &updated)
Set update timestamp, default normally "last-modified".
void setContentLengthHeader(qulonglong size)
Set the content length.
qulonglong getContentLengthHeader() const
Header content length.
QString getLoadTimeString() const
Load time as string.
QString getLoadTimeStringWithStartedHint() const
Load time as string.
void setMessage(const swift::misc::CStatusMessage &lastErrorOrWarning)
Set the error/warning message.
qint64 getLoadTimeMs() const
Load time in ms (from request to response).
Response from our database (depending on JSON DB backend generates).
bool isRestricted() const
Incremental data, restricted by query?
void setJsonArray(const QJsonArray &value)
Set the JSON array.
bool isLoadedFromDb() const
Is loaded from database.