swift
Loading...
Searching...
No Matches
threadedreader.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <QCoreApplication>
7#include <QMetaObject>
8#include <QReadLocker>
9#include <QThread>
10#include <QTimer>
11#include <QWriteLocker>
12
13#include "core/application.h"
14#include "misc/logmessage.h"
16#include "misc/threadutils.h"
17#include "misc/verify.h"
18
19using namespace swift::misc;
20using namespace swift::misc::network;
21using namespace swift::core::vatsim;
22
23namespace swift::core
24{
26 {
28 return cats;
29 }
30
32
37
39 {
40 QReadLocker lock(&m_lock);
41 return m_updateTimestamp;
42 }
43
45 {
46 QWriteLocker lock(&m_lock);
47 m_updateTimestamp = updateTimestamp;
48 }
49
51 {
53 return m_urlReadLog;
54 }
55
56 bool CThreadedReader::didContentChange(const QString &content, int startPosition)
57 {
58 size_t oldHash = 0;
59 {
61 oldHash = m_contentHash;
62 }
63 size_t newHash = qHash(startPosition < 0 ? content : content.mid(startPosition));
64 if (oldHash == newHash)
65 {
66 return false;
67 }
68 {
70 m_contentHash = newHash;
71 }
72 return true;
73 }
74
75 bool CThreadedReader::isMarkedAsFailed() const { return m_markedAsFailed; }
76
77 void CThreadedReader::setMarkedAsFailed(bool failed) { m_markedAsFailed = failed; }
78
80 {
82 return m_urlReadLog;
83 }
84
86 {
87 Q_ASSERT_X(QCoreApplication::instance()->thread() != QThread::currentThread(), Q_FUNC_INFO,
88 "Needs to run in own thread");
89 Q_ASSERT_X(this->thread() == QThread::currentThread(), Q_FUNC_INFO, "Wrong object thread");
90 }
91
93 {
94 // sApp->hasWebDataServices() cannot be used, as some readers are already used during init phase
95 if (!this->isEnabled())
96 {
97 return false;
98 }
99
100 // MS 2019-02-23 isAbandoned() check only makes sense when called by worker thread (T541)
101 if (CThreadUtils::isInThisThread(this) && this->isAbandoned())
102 {
103 return false;
104 }
105
106 if (!m_unitTest && (!sApp || sApp->isShuttingDown()))
107 {
108 return false;
109 }
110 return true;
111 }
112
114 {
115 QWriteLocker wl(&m_lock);
116 const CUrlLogList outdatedPendingUrls = m_urlReadLog.findOutdatedPending(OutdatedPendingCallMs);
117 if (!outdatedPendingUrls.isEmpty())
118 {
119 CLogMessage(this).warning(u"Detected outdated reader pending calls: '%1'")
120 << outdatedPendingUrls.toQString(true);
121 m_urlReadLog.removeOlderThanNowMinusOffset(OutdatedPendingCallMs); // clean up
122 }
123
124 const int id = m_urlReadLog.addPendingUrl(url);
125 wl.unlock();
126
127 // returned QNetworkReply normally nullptr since QAM is in different thread
128 QNetworkReply *nr = sApp->getFromNetwork(url, id, callback, { this, &CThreadedReader::networkReplyProgress });
129 return nr;
130 }
131
132 QPair<qint64, qint64> CThreadedReader::getNetworkReplyBytes() const
133 {
135 }
136
137 void CThreadedReader::networkReplyProgress(int logId, qint64 current, qint64 max, const QUrl &url)
138 {
139 // max can be -1 if file size is not available
140 m_networkReplyProgress = (current > 0 && max > 0) ? static_cast<int>((current * 100) / max) : -1;
141 m_networkReplyCurrent = current;
142 m_networkReplyMax = max;
143
144 Q_UNUSED(url);
145 Q_UNUSED(logId);
146 }
147
149 {
150 if (!reply)
151 {
152 return;
153 }
154 QWriteLocker wl(&m_lock);
155 m_urlReadLog.markAsReceived(reply, reply->error() == QNetworkReply::NoError);
156 }
157
158 void CThreadedReader::logInconsistentData(const CStatusMessage &msg, const char *funcInfo)
159 {
160 if (msg.isEmpty())
161 {
162 return;
163 }
164 CStatusMessage logMsg(msg);
166 if (funcInfo)
167 {
168 const QByteArray m(logMsg.getMessage().toLatin1());
169 SWIFT_AUDIT_X(false, funcInfo, m.constData());
170 }
172 }
173} // namespace swift::core
std::atomic_llong m_networkReplyCurrent
current bytes
QDateTime getUpdateTimestamp() const
Thread safe, get update timestamp.
QPair< qint64, qint64 > getNetworkReplyBytes() const
Max./current bytes.
void setUpdateTimestamp(const QDateTime &updateTimestamp=QDateTime::currentDateTimeUtc())
Thread safe, set update timestamp.
static const QStringList & getLogCategories()
Log categories.
virtual void networkReplyProgress(int logId, qint64 current, qint64 max, const QUrl &url)
Network request progress.
static void logInconsistentData(const swift::misc::CStatusMessage &msg, const char *funcInfo=nullptr)
Use this to log inconsistent data.
swift::misc::network::CUrlLogList getReadLog() const
Get the read log.
void setMarkedAsFailed(bool failed)
Set marker for read failed.
std::atomic_int m_networkReplyProgress
Progress percentage 0...100.
bool isMarkedAsFailed() const
Is marked as read failed.
void threadAssertCheck() const
Make sure everything runs correctly in own thread.
void logNetworkReplyReceived(QNetworkReply *reply)
Network reply received, mark in m_urlReadLog.
QReadWriteLock m_lock
lock which can be used from the derived classes
bool didContentChange(const QString &content, int startPosition=-1)
Stores new content hash and returns if content changed (based on hash value.
swift::misc::network::CUrlLogList getUrlLogList() const
Get the URL log list.
CThreadedReader(const CThreadedReader &)=delete
Copy constructor.
QNetworkReply * getFromNetworkAndLog(const swift::misc::network::CUrl &url, const swift::misc::CSlot< void(QNetworkReply *)> &callback)
Get request from network, and log with m_urlReadLog.
bool doWorkCheck() const
Still enabled etc.?
qint64 lastModifiedMsSinceEpoch(QNetworkReply *nwReply) const
When was reply last modified, -1 if N/A.
std::atomic_llong m_networkReplyMax
max bytes
bool isEnabled() const
Enabled (running)?
Definition worker.h:346
const QObject * owner() const
Owner of the worker.
Definition worker.h:352
CContinuousWorker(QObject *owner, const QString &name)
Constructor.
Definition worker.cpp:168
static const QString & worker()
Background task.
static const QString & dataInconsistency()
Data inconsistency.
Class for emitting a log message.
Definition logmessage.h:27
static void preformatted(const CStatusMessage &statusMessage)
Sends a verbatim, preformatted message to the log.
bool isEmpty() const
Message empty.
Derived & warning(const char16_t(&format)[N])
Set the severity to warning, providing a format string.
bool isEmpty() const
Synonym for empty.
Definition sequence.h:285
Callable wrapper for a member function with function signature F.
Definition slot.h:65
Streamable status message, e.g.
QString getMessage() const
Message.
void addCategory(const CLogCategory &category)
Add category, avoids duplicates.
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
QString toQString(bool i18n=false) const
Cast as QString.
Definition mixinstring.h:74
static qint64 lastModifiedMsSinceEpoch(const QNetworkReply *nwReply)
Last modified from reply.
Value object encapsulating information of a location, kind of simplified CValueObject compliant versi...
Definition url.h:27
Value object encapsulating a list of voice rooms.
Definition urlloglist.h:26
CUrlLogList findOutdatedPending(int outdatedOffsetMs) const
Find outdated pending log entries.
int addPendingUrl(const CUrl &url, int maxNumber=10)
Add a pending URL.
Backend services of the swift project, like dealing with the network or the simulators.
Definition actionbind.cpp:7
Free functions in swift::misc.
size_t qHash(const std::string &key, uint seed)
std::string qHash
Definition metaclass.h:84
const char * constData() const const
QCoreApplication * instance()
QNetworkReply::NetworkError error() const const
QObject(QObject *parent)
QThread * thread() const const
QString mid(qsizetype position, qsizetype n) &&
QByteArray toLatin1() const const
QThread * currentThread()
#define SWIFT_AUDIT_X(COND, WHERE, WHAT)
A weaker kind of verify.
Definition verify.h:38