summaryrefslogtreecommitdiffstats
path: root/src/network/webtask.cpp
blob: fc7f1b3f356d18e6d24e55b1f49fdf995a9848d0 (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
#include "network/webtask.h"

#include <QThread>
#include <QTimerEvent>
#include <mutex> // std::once_flag

#include "util/assert.h"
#include "util/counter.h"
#include "util/logger.h"

namespace mixxx {

namespace network {

namespace {

const Logger kLogger("mixxx::network::WebTask");

constexpr int kInvalidTimerId = -1;

// count = even number (ctor + dtor)
// sum = 0 (no memory leaks)
Counter s_instanceCounter(QStringLiteral("mixxx::network::WebTask"));

std::once_flag registerMetaTypesOnceFlag;

void registerMetaTypesOnce() {
    WebResponse::registerMetaType();
    CustomWebResponse::registerMetaType();
}

bool readStatusCode(
        const QNetworkReply* reply,
        int* statusCode) {
    DEBUG_ASSERT(statusCode);
    const QVariant statusCodeAttr = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    bool statusCodeValid = false;
    const int statusCodeValue = statusCodeAttr.toInt(&statusCodeValid);
    VERIFY_OR_DEBUG_ASSERT(statusCodeValid && HttpStatusCode_isValid(statusCodeValue)) {
        kLogger.warning()
                << "Invalid or missing status code attribute"
                << statusCodeAttr;
    }
    else {
        *statusCode = statusCodeValue;
    }
    return statusCodeValid;
}

} // anonymous namespace

/*static*/ void WebResponse::registerMetaType() {
    qRegisterMetaType<WebResponse>("mixxx::network::WebResponse");
}

QDebug operator<<(QDebug dbg, const WebResponse& arg) {
    return dbg
        << "WebResponse{"
        << arg.replyUrl
        << arg.statusCode
        << '}';
}

/*static*/ void CustomWebResponse::registerMetaType() {
    qRegisterMetaType<CustomWebResponse>("mixxx::network::CustomWebResponse");
}

QDebug operator<<(QDebug dbg, const CustomWebResponse& arg) {
    return dbg
        << "CustomWebResponse{"
        << static_cast<const WebResponse&>(arg)
        << arg.content
        << '}';
}

WebTask::WebTask(
        QNetworkAccessManager* networkAccessManager,
        QObject* parent)
        : QObject(parent),
          m_networkAccessManager(networkAccessManager),
          m_timeoutTimerId(kInvalidTimerId),
          m_status(Status::Idle) {
    std::call_once(registerMetaTypesOnceFlag, registerMetaTypesOnce);
    DEBUG_ASSERT(m_networkAccessManager);
    s_instanceCounter.increment(1);
}

WebTask::~WebTask() {
    s_instanceCounter.increment(-1);
}

void WebTask::onAborted(
        QUrl&& requestUrl) {
    DEBUG_ASSERT(m_status == Status::Aborted);
    VERIFY_OR_DEBUG_ASSERT(
            isSignalFuncConnected(&WebTask::aborted)) {
        kLogger.warning()
                << "Unhandled abort signal"
                << requestUrl;
        deleteLater();
        return;
    }
    emit aborted(
            std::move(requestUrl));
}

void WebTask::onTimedOut(
        QUrl&& requestUrl) {
    DEBUG_ASSERT(m_status == Status::TimedOut);
    onNetworkError(
            std::move(requestUrl),
            QNetworkReply::TimeoutError,
            tr("Client-side network timeout"),
            QByteArray());
}

void WebTask::onNetworkError(
        QUrl&& requestUrl,
        QNetworkReply::NetworkError errorCode,
        QString&& errorString,
        QByteArray&& errorContent) {
    VERIFY_OR_DEBUG_ASSERT(
            isSignalFuncConnected(&WebTask::networkError)) {
        kLogger.warning()
                << "Unhandled network error signal"
                << requestUrl
                << errorCode
                << errorString
                << errorContent;
        deleteLater();
        return;
    }
    emit networkError(
            std::move(requestUrl),
            errorCode,
            std::move(errorString),
            std::move(errorContent));
}

void WebTask::invokeStart(int timeoutMillis) {
    QMetaObject::invokeMethod(
            this,
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
            "slotStart",
            Qt::AutoConnection,
            Q_ARG(int, timeoutMillis)
#else
            [this, timeoutMillis] {
                this->slotStart(timeoutMillis);
            }
#endif
    );
}

void WebTask::invokeAbort() {
    QMetaObject::invokeMethod(
            this,
#if QT_VERSION < QT_VERSION_CHECK(5, 10, 0)
            "slotAbort"
#else
            [this] {
                this->slotAbort();
            }
#endif
    );
}

void WebTask::slotStart(int timeoutMillis) {
    DEBUG_ASSERT(thread() == QThread::currentThread());
    DEBUG_ASSERT(m_status != Status::Pending);
    VERIFY_OR_DEBUG_ASSERT(m_networkAccessManager) {
        onNetworkError(
                QUrl(),
                QNetworkReply::NetworkSessionFailedError,
                tr("No network access"),
                QByteArray());
        return;
    }

    kLogger.debug()
            << "Starting...";
    m_status = Status::Idle;
    if (!doStart(m_networkAccessManager, timeoutMillis)) {
        // Still idle, because we are in the same thread.
        // The callee is not supposed to abort a request
        // before it has beeen started successfully.
        DEBUG_ASSERT(m_status == Status::Idle);
        onNetworkError(
                QUrl(),
                QNetworkReply::OperationCanceledError,
                tr("Start of network task has been aborted"),
                QByteArray());
        return;
    }
    // Still idle after the request has been started
    // successfully, i.e. nothing happend yet in this
    // thread.
    DEBUG_ASSERT(m_status == Status::Idle);
    m_status = Status::Pending;

    DEBUG_ASSERT(m_timeoutTimerId == kInvalidTimerId);
    if (timeoutMillis > 0) {
        m_timeoutTimerId = startTimer(timeoutMillis);
        DEBUG_ASSERT(m_timeoutTimerId != kInvalidTimerId);
    }
}

QUrl WebTask::abortPendingNetworkReply(
        QNetworkReply* pendingNetworkReply) {
    DEBUG_ASSERT(thread() == QThread::currentThread());
    DEBUG_ASSERT(pendingNetworkReply);
    if (pendingNetworkReply->isRunning()) {
        pendingNetworkReply->abort();
        // Suspend until finished
        return QUrl();
    }
    return pendingNetworkReply->request().url();
}

QUrl WebTask::timeOutPendingNetworkReply(
        QNetworkReply* pendingNetworkReply) {
    DEBUG_ASSERT(thread() == QThread::currentThread());
    DEBUG_ASSERT(pendingNetworkReply);
    if (pendingNetworkReply->isRunning()) {
        //pendingNetworkReply->abort();
        // Don't suspend until finished, i.e. abort and then
        // delete the pending network request instantly
    }
    return pendingNetworkReply->request().url();
}

QUrl WebTask::abort() {
    DEBUG_ASSERT(thread() == QThread::currentThread());
    if (m_status != Status::Pending) {
        DEBUG_ASSERT(m_timeoutTimerId == kInvalidTimerId);
        return QUrl();
    }
    if (m_timeoutTimerId != kInvalidTimerId) {
        killTimer(m_timeoutTimerId);
        m_timeoutTimerId = kInvalidTimerId;
    }
    m_status = Status::Aborted;
    kLogger.debug()
            << "Aborting...";
    QUrl url = doAbort();
    onAborted(QUrl(url));
    return url;
}

void WebTask::slotAbort() {
    abort();
}

void WebTask::timerEvent(QTimerEvent* event) {
    DEBUG_ASSERT(thread() == QThread::currentThread());
    const auto timerId = event->timerId();
    DEBUG_ASSERT(timerId != kInvalidTimerId);
    if (timerId != m_timeoutTimerId) {
        // ignore
        return;
    }
    killTimer(m_timeoutTimerId);
    m_timeoutTimerId = kInvalidTimerId;
    if (m_status != Status::Aborted) {
        m_status = Status::TimedOut;
    }
    kLogger.debug()
            << "Timed out";
    onTimedOut(doTimeOut());
}

QPair<QNetworkReply*, HttpStatusCode> WebTask::receiveNetworkReply() {
    DEBUG_ASSERT(thread() == QThread::currentThread());
    DEBUG_ASSERT(m_status != Status::Idle);
    auto* const networkReply = qobject_cast<QNetworkReply*>(sender());
    HttpStatusCode statusCode = kHttpStatusCodeInvalid;
    VERIFY_OR_DEBUG_ASSERT(networkReply) {
        return qMakePair(nullptr, statusCode);
    }
    networkReply->deleteLater();

    if (m_timeoutTimerId != kInvalidTimerId) {
        killTimer(m_timeoutTimerId);
        m_timeoutTimerId = kInvalidTimerId;
    }

    if (m_status == Status::Aborted) {
        onAborted(networkReply->request().url());
        return qMakePair(nullptr, statusCode);
    }
    m_status = Status::Finished;

    if (networkReply->error() != QNetworkReply::NetworkError::NoError) {
        onNetworkError(
                networkReply->request().url(),
                networkReply->error(),
                networkReply->errorString(),
                networkReply->readAll());
        return qMakePair(nullptr, statusCode);
    }

    if (kLogger.debugEnabled()) {
        if (networkReply->url() == networkReply