8#include <QJsonDocument>
10#include <QJsonValueRef>
12#include <QNetworkReply>
15#include <QStringBuilder>
17#include <QWriteLocker>
33using namespace swift::misc::db;
34using namespace swift::misc::network;
51 Q_ASSERT_X(
hasStarted(), Q_FUNC_INFO,
"Thread was not started yet!");
59 CEntityFlags::Entity allEntities = entities;
63 CEntityFlags::Entity currentEntity =
71 const CDbFlags::DataRetrievalMode rm = config.getRetrievalMode();
77 const bool rmDbReadingOrShared =
79 const int currentEntityCount = this->
getCacheCount(currentEntity);
93 Q_ASSERT_X(!
getBaseUrl(rmDbOrSharedFlag).isEmpty(), Q_FUNC_INFO,
"Wrong retrieval mode");
97 const bool changedUrl = this->
hasChangedUrl(currentEntity, oldUrlInfo, newUrlInfo);
101 const qint64 latestEntityTimestamp =
103 Q_ASSERT_X(latestEntityTimestamp >= 0, Q_FUNC_INFO,
"Missing timestamp");
104 if (!changedUrl && cacheTimestamp >= latestEntityTimestamp && cacheTimestamp >= 0 &&
105 latestEntityTimestamp >= 0)
108 cachedEntities |= currentEntity;
110 << currentEntityName << cacheTs.
toString() << cacheTimestamp;
114 Q_ASSERT_X(rmDbReadingOrShared, Q_FUNC_INFO,
"Wrong retrieval mode");
117 dbEntities |= currentEntity;
121 sharedEntities |= currentEntity;
127 u
"Data location for '%1' changed ('%2'->'%3'), will override cache for reading '%4'")
129 << rmDbOrSharedFlagString;
133 CLogMessage(
this).
info(u
"Cache for '%1' outdated, latest entity (%2, %3), reading '%4'")
134 << currentEntityName << latestEntityTs.
toString() << latestEntityTimestamp
135 << rmDbOrSharedFlagString;
141 if (!rmDbReadingOrShared)
143 CLogMessage(
this).
info(u
"No DB or shared reading for '%1', read mode is: '%2'")
144 << currentEntityName << rmString;
148 CLogMessage(
this).
info(u
"No DB info objects for '%1', read mode is: '%2'")
149 << currentEntityName << rmString;
151 if (currentEntityCount > 0)
154 << currentEntityName << currentEntityCount;
160 if (!rmDbReadingOrShared)
163 CLogMessage(
this).
info(u
"Triggered reading cache for '%1', read mode: %2")
164 << currentEntityName << rmString;
169 CLogMessage(
this).
info(u
"No info object for '%1', triggered reading cache, read mode: %2")
170 << currentEntityName << rmString;
173 cachedEntities |= currentEntity;
179 Q_ASSERT_X(rmDbReadingOrShared, Q_FUNC_INFO,
"Wrong retrieval mode");
182 dbEntities |= currentEntity;
186 sharedEntities |= currentEntity;
222 bool checkCacheTsUpfront)
228 if (checkCacheTsUpfront)
231 if (newerHeaderEntities != entities)
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)")
247 if (!sApp || sApp->isShuttingDown())
258 entities = newerHeaderEntities;
279 if (!sApp || sApp->isShuttingDown() || !myself)
283 this->
read(entities, mode, newerThan);
290 Q_ASSERT_X(nwReply, Q_FUNC_INFO,
"missing reply");
305 CDatabaseReader::stringToDatastoreResponse(dataFileData, datastoreResponse);
308 return datastoreResponse;
316 return headerResponse;
322 Q_ASSERT_X(nwReply, Q_FUNC_INFO,
"Missing reply");
373 if (!sApp->hasWebDataServices())
377 if (!sApp->getWebDataServices()->getDbInfoDataReader())
381 return sApp->getWebDataServices()->getDbInfoDataReader()->getInfoObjects();
387 if (!sApp->hasWebDataServices())
391 if (!sApp->getWebDataServices()->getSharedInfoDataReader())
395 return sApp->getWebDataServices()->getSharedInfoDataReader()->getInfoObjects();
481 if (!headerTimestamp.
isValid())
485 return headerTimestamp > cacheTs;
498 if (!sharedInfoTimestamp.
isValid())
502 return sharedInfoTimestamp > cacheTs;
514 newerEntities |= currentEntity;
518 return newerEntities;
530 newerEntities |= currentEntity;
534 return newerEntities;
539 return m_config.findFirstOrDefaultForEntity(entity);
550 CEntityFlags::Entity cachedEntitiesToEmit = cachedEntities;
552 while (currentCachedEntity)
555 if (!onlyIfHasData || c > 0)
558 emitted |= currentCachedEntity;
586 if (!sApp || sApp->isShuttingDown())
594 case CDbFlags::Shared:
return sApp->getGlobalSetup().getSharedDbDataDirectoryUrl();
595 default: qFatal(
"Wrong mode");
break;
606 Q_ASSERT_X(!currentUrl.
isEmpty(), Q_FUNC_INFO,
"No base URL");
610 return old != current;
638 CLogMessage(
this).
info(u
"Received header for shared file of '%1' from '%2'")
684 return ts > threshold;
697 const bool overrideNewerOnly =
true;
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")
726 Q_ASSERT_X(nwReply, Q_FUNC_INFO,
"Missing network reply");
741 if (!overrideNewerOnly)
753 if (fileTs > cacheTs)
817 static const QString p(
"latestTimestamp");
830 static const CUrl dbUrl(sApp->getGlobalSetup().getDbRootDirectoryUrl());
839 void CDatabaseReader::stringToDatastoreResponse(
const QString &jsonContent,
840 JsonDatastoreResponse &datastoreResponse)
842 const int status = datastoreResponse.getHttpStatusCode();
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())));
858 static const QString errorMsg =
"Looks like PHP errror, status %1, URL: '%2', msg: %3";
860 datastoreResponse.setMessage(
862 errorMsg.
arg(status).
arg(datastoreResponse.getUrlString(), phpErrorMessage)));
866 static const QString errorMsg =
"Empty JSON document, URL: '%1', load time: %2";
867 datastoreResponse.setMessage(
869 errorMsg.
arg(datastoreResponse.getUrlString(),
870 datastoreResponse.getLoadTimeStringWithStartedHint())));
878 datastoreResponse.setJsonArray(jsonResponse.
array());
883 const QJsonObject responseObject(jsonResponse.
object());
884 datastoreResponse.setJsonArray(responseObject[
"data"].toArray());
885 const QString ts(responseObject[
"latest"].
toString());
888 datastoreResponse.setRestricted(responseObject[
"restricted"].toBool());
900 m_arraySize = value.
size();
905 static const QString s(
"DB: %1 | restricted: %2 | array: %3 | string size: %4 | content: %5");
925 if (m_requestStarted < 0)
930 static const QString s(
"%1 load time, started %2ms before now");
936 Q_ASSERT_X(nwReply, Q_FUNC_INFO,
"Need valid reply");
944 m_requestStarted =
start;
945 m_responseReceived = now;
951 m_httpStatusCode = qvStatusCode.
toInt();
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.
QReadWriteLock m_statusLock
Lock.
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 ¤tUrl)
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.
void start(QThread::Priority priority=QThread::InheritPriority)
Starts a thread and moves the worker into it.
static const QString & swiftDbWebservice()
Webservice with swift DB.
static const QString & webservice()
Webservice.
Class for emitting a log message.
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.
bool isEmpty() const
Synonym for empty.
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.
bool hasStarted() const
True if the worker has started.
QDateTime getUtcTimestamp() const
Get timestamp.
static QDateTime parseTimestamp(const QString ×tamp)
Parse a timestamp object.
DataRetrievalModeFlag
Which data to read, requires corresponding readers.
@ DbReadingOrShared
read from DB or shared
@ Canceled
canceled DB reading
@ Unspecified
Unspecified.
@ DbReading
directly from DB
@ Ignore
ignore this entity
@ SharedInfoOnly
shared info file only
static DataRetrievalModeFlag modeToModeFlag(DataRetrievalMode mode)
Mode to flag.
static QString flagToString(DataRetrievalModeFlag flag)
Convert to string.
Info about the latest models.
static const QString & sharedInfoFileName()
Get shared info file name.
static const QStringList & sharedFileNames()
The shared file names.
bool isValid() const
Valid?
static const QString & entityToSharedName(network::CEntityFlags::Entity entity)
Get shared file name.
static const QString & entityToServiceName(network::CEntityFlags::Entity entity)
Get service file name.
Value object encapsulating a list of info objects.
CDbInfo findFirstByEntityOrDefault(swift::misc::network::CEntityFlags::Entity entity) const
Find by entity.
QString toQString(bool i18n=false) const
Cast as QString.
What and state of reading from web services.
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
@ DbInfoObjectEntity
info about DB data (kind of metadata)
@ ReadFinishedRestricted
finished a timestamp restricted read
@ ReadFinished
reading done
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...
const QString & getHost() const
Get host.
bool isEmpty() const
Empty.
CUrl withAppendedPath(const QString &path) const
Append path.
QString getFullUrl(bool withQuery=true) const
Qualified name.
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.
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
qsizetype size() const const
QJsonArray array() const const
bool isArray() const const
bool isEmpty() const const
QJsonObject object() const const
QVariant attribute(QNetworkRequest::Attribute code) const const
virtual void close() override
QNetworkReply::NetworkError error() const const
bool isFinished() const const
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
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
Response from our database (depending on JSON DB backend generates).
int getArraySize() const
Number of elements.
bool isRestricted() const
Incremental data, restricted by query?
QString toQString() const
String info.
void setJsonArray(const QJsonArray &value)
Set the JSON array.
bool isLoadedFromDb() const
Is loaded from database.
void setStringSize(int size)
Set string size.