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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
|
/*
* Copyright (C) 2016 Christian Mollekopf <mollekopf@kolabsys.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "genericresource.h"
#include "entitybuffer.h"
#include "pipeline.h"
#include "queuedcommand_generated.h"
#include "createentity_generated.h"
#include "modifyentity_generated.h"
#include "deleteentity_generated.h"
#include "inspection_generated.h"
#include "notification_generated.h"
#include "domainadaptor.h"
#include "commands.h"
#include "index.h"
#include "log.h"
#include "definitions.h"
#include "bufferutils.h"
#include "adaptorfactoryregistry.h"
#include "synchronizer.h"
#include <QUuid>
#include <QDataStream>
#include <QTime>
//This is the resources entity type, and not the domain type
#define ENTITY_TYPE_MAIL "mail"
#define ENTITY_TYPE_FOLDER "folder"
static int sBatchSize = 100;
// This interval directly affects the roundtrip time of single commands
static int sCommitInterval = 10;
using namespace Sink;
#undef DEBUG_AREA
#define DEBUG_AREA "resource.commandprocessor"
/**
* Drives the pipeline using the output from all command queues
*/
class CommandProcessor : public QObject
{
Q_OBJECT
typedef std::function<KAsync::Job<void>(void const *, size_t)> InspectionFunction;
public:
CommandProcessor(Sink::Pipeline *pipeline, QList<MessageQueue *> commandQueues) : QObject(), mPipeline(pipeline), mCommandQueues(commandQueues), mProcessingLock(false)
{
mLowerBoundRevision = Storage::maxRevision(mPipeline->storage().createTransaction(Storage::ReadOnly, [](const Sink::Storage::Error &error) {
Warning() << error.message;
}));
for (auto queue : mCommandQueues) {
const bool ret = connect(queue, &MessageQueue::messageReady, this, &CommandProcessor::process);
Q_UNUSED(ret);
}
}
void setOldestUsedRevision(qint64 revision)
{
mLowerBoundRevision = revision;
}
void setInspectionCommand(const InspectionFunction &f)
{
mInspect = f;
}
signals:
void error(int errorCode, const QString &errorMessage);
private:
bool messagesToProcessAvailable()
{
for (auto queue : mCommandQueues) {
if (!queue->isEmpty()) {
return true;
}
}
return false;
}
private slots:
void process()
{
if (mProcessingLock) {
return;
}
mProcessingLock = true;
auto job = processPipeline()
.then<void>([this]() {
mProcessingLock = false;
if (messagesToProcessAvailable()) {
process();
}
})
.exec();
}
KAsync::Job<qint64> processQueuedCommand(const Sink::QueuedCommand *queuedCommand)
{
Log() << "Processing command: " << Sink::Commands::name(queuedCommand->commandId());
// Throw command into appropriate pipeline
switch (queuedCommand->commandId()) {
case Sink::Commands::DeleteEntityCommand:
return mPipeline->deletedEntity(queuedCommand->command()->Data(), queuedCommand->command()->size());
case Sink::Commands::ModifyEntityCommand:
return mPipeline->modifiedEntity(queuedCommand->command()->Data(), queuedCommand->command()->size());
case Sink::Commands::CreateEntityCommand:
return mPipeline->newEntity(queuedCommand->command()->Data(), queuedCommand->command()->size());
case Sink::Commands::InspectionCommand:
if (mInspect) {
return mInspect(queuedCommand->command()->Data(), queuedCommand->command()->size()).then<qint64>([]() { return -1; });
} else {
return KAsync::error<qint64>(-1, "Missing inspection command.");
}
default:
return KAsync::error<qint64>(-1, "Unhandled command");
}
}
KAsync::Job<qint64, qint64> processQueuedCommand(const QByteArray &data)
{
flatbuffers::Verifier verifyer(reinterpret_cast<const uint8_t *>(data.constData()), data.size());
if (!Sink::VerifyQueuedCommandBuffer(verifyer)) {
Warning() << "invalid buffer";
// return KAsync::error<void, qint64>(1, "Invalid Buffer");
}
auto queuedCommand = Sink::GetQueuedCommand(data.constData());
const auto commandId = queuedCommand->commandId();
Trace() << "Dequeued Command: " << Sink::Commands::name(commandId);
return processQueuedCommand(queuedCommand)
.then<qint64, qint64>(
[commandId](qint64 createdRevision) -> qint64 {
Trace() << "Command pipeline processed: " << Sink::Commands::name(commandId);
return createdRevision;
},
[](int errorCode, QString errorMessage) {
// FIXME propagate error, we didn't handle it
Warning() << "Error while processing queue command: " << errorMessage;
});
}
// Process all messages of this queue
KAsync::Job<void> processQueue(MessageQueue *queue)
{
auto time = QSharedPointer<QTime>::create();
return KAsync::start<void>([this]() { mPipeline->startTransaction(); })
.then(KAsync::dowhile([queue]() { return !queue->isEmpty(); },
[this, queue, time](KAsync::Future<void> &future) {
queue->dequeueBatch(sBatchSize,
[this, time](const QByteArray &data) {
time->start();
return KAsync::start<void>([this, data, time](KAsync::Future<void> &future) {
processQueuedCommand(data)
.then<void, qint64>([&future, this, time](qint64 createdRevision) {
Trace() << "Created revision " << createdRevision << ". Processing took: " << Log::TraceTime(time->elapsed());
future.setFinished();
})
.exec();
});
})
.then<void>([&future, queue]() { future.setFinished(); },
[&future](int i, QString error) {
if (i != MessageQueue::ErrorCodes::NoMessageFound) {
Warning() << "Error while getting message from messagequeue: " << error;
}
future.setFinished();
})
.exec();
}))
.then<void>([this]() { mPipeline->commit(); });
}
KAsync::Job<void> processPipeline()
{
auto time = QSharedPointer<QTime>::create();
time->start();
mPipeline->startTransaction();
Trace() << "Cleaning up from " << mPipeline->cleanedUpRevision() + 1 << " to " << mLowerBoundRevision;
for (qint64 revision = mPipeline->cleanedUpRevision() + 1; revision <= mLowerBoundRevision; revision++) {
mPipeline->cleanupRevision(revision);
}
mPipeline->commit();
Trace() << "Cleanup done." << Log::TraceTime(time->elapsed());
// Go through all message queues
auto it = QSharedPointer<QListIterator<MessageQueue *>>::create(mCommandQueues);
return KAsync::dowhile([it]() { return it->hasNext(); },
[it, this](KAsync::Future<void> &future) {
auto time = QSharedPointer<QTime>::create();
time->start();
auto queue = it->next();
processQueue(queue)
.then<void>([&future, time]() {
Trace() << "Queue processed." << Log::TraceTime(time->elapsed());
future.setFinished();
})
.exec();
});
}
private:
Sink::Pipeline *mPipeline;
// Ordered by priority
QList<MessageQueue *> mCommandQueues;
bool mProcessingLock;
// The lowest revision we no longer need
qint64 mLowerBoundRevision;
InspectionFunction mInspect;
};
#undef DEBUG_AREA
#define DEBUG_AREA "resource"
GenericResource::GenericResource(const QByteArray &resourceType, const QByteArray &resourceInstanceIdentifier, const QSharedPointer<Pipeline> &pipeline )
: Sink::Resource(),
mUserQueue(Sink::storageLocation(), resourceInstanceIdentifier + ".userqueue"),
mSynchronizerQueue(Sink::storageLocation(), resourceInstanceIdentifier + ".synchronizerqueue"),
mResourceType(resourceType),
mResourceInstanceIdentifier(resourceInstanceIdentifier),
mPipeline(pipeline ? pipeline : QSharedPointer<Sink::Pipeline>::create(resourceInstanceIdentifier)),
mError(0),
mClientLowerBoundRevision(std::numeric_limits<qint64>::max())
{
mPipeline->setResourceType(mResourceType);
mProcessor = new CommandProcessor(mPipeline.data(), QList<MessageQueue *>() << &mUserQueue << &mSynchronizerQueue);
mProcessor->setInspectionCommand([this](void const *command, size_t size) {
flatbuffers::Verifier verifier((const uint8_t *)command, size);
if (Sink::Commands::VerifyInspectionBuffer(verifier)) {
auto buffer = Sink::Commands::GetInspection(command);
int inspectionType = buffer->type();
QByteArray inspectionId = BufferUtils::extractBuffer(buffer->id());
QByteArray entityId = BufferUtils::extractBuffer(buffer->entityId());
QByteArray domainType = BufferUtils::extractBuffer(buffer->domainType());
QByteArray property = BufferUtils::extractBuffer(buffer->property());
QByteArray expectedValueString = BufferUtils::extractBuffer(buffer->expectedValue());
QDataStream s(expectedValueString);
QVariant expectedValue;
s >> expectedValue;
inspect(inspectionType, inspectionId, domainType, entityId, property, expectedValue)
.then<void>(
[=]() {
Log_area("resource.inspection") << "Inspection was successful: " << inspectionType << inspectionId << entityId;
Sink::Notification n;
n.type = Sink::Commands::NotificationType_Inspection;
n.id = inspectionId;
n.code = Sink::Commands::NotificationCode_Success;
emit notify(n);
},
[=](int code, const QString &message) {
Warning_area("resource.inspection") << "Inspection failed: " << inspectionType << inspectionId << entityId << message;
Sink::Notification n;
n.type = Sink::Commands::NotificationType_Inspection;
n.message = message;
n.id = inspectionId;
n.code = Sink::Commands::NotificationCode_Failure;
emit notify(n);
})
.exec();
return KAsync::null<void>();
}
return KAsync::error<void>(-1, "Invalid inspection command.");
});
QObject::connect(mProcessor, &CommandProcessor::error, [this](int errorCode, const QString &msg) { onProcessorError(errorCode, msg); });
QObject::connect(mPipeline.data(), &Pipeline::revisionUpdated, this, &Resource::revisionUpdated);
mClientLowerBoundRevision = mPipeline->cleanedUpRevision();
mCommitQueueTimer.setInterval(sCommitInterval);
mCommitQueueTimer.setSingleShot(true);
QObject::connect(&mCommitQueueTimer, &QTimer::timeout, &mUserQueue, &MessageQueue::commit);
}
GenericResource::~GenericResource()
{
delete mProcessor;
}
KAsync::Job<void> GenericResource::inspect(
int inspectionType, const QByteArray &inspectionId, const QByteArray &domainType, const QByteArray &entityId, const QByteArray &property, const QVariant &expectedValue)
{
Warning() << "Inspection not implemented";
return KAsync::null<void>();
}
void GenericResource::enableChangeReplay(bool enable)
{
Q_ASSERT(mChangeReplay);
if (enable) {
QObject::connect(mPipeline.data(), &Pipeline::revisionUpdated, mChangeReplay.data(), &ChangeReplay::revisionChanged, Qt::QueuedConnection);
QObject::connect(mChangeReplay.data(), &ChangeReplay::changesReplayed, this, &GenericResource::updateLowerBoundRevision);
mChangeReplay->revisionChanged();
} else {
QObject::disconnect(mPipeline.data(), &Pipeline::revisionUpdated, mChangeReplay.data(), &ChangeReplay::revisionChanged);
QObject::disconnect(mChangeReplay.data(), &ChangeReplay::changesReplayed, this, &GenericResource::updateLowerBoundRevision);
}
}
void GenericResource::setupPreprocessors(const QByteArray &type, const QVector<Sink::Preprocessor *> &preprocessors)
{
mPipeline->setPreprocessors(type, preprocessors);
}
void GenericResource::setupSynchronizer(const QSharedPointer<Synchronizer> &synchronizer)
{
mSynchronizer = synchronizer;
mSynchronizer->setup([this](int commandId, const QByteArray &data) {
enqueueCommand(mSynchronizerQueue, commandId, data);
});
}
void GenericResource::setupChangereplay(const QSharedPointer<ChangeReplay> &changeReplay)
{
mChangeReplay = changeReplay;
mProcessor->setOldestUsedRevision(mChangeReplay->getLastReplayedRevision());
enableChangeReplay(true);
}
void GenericResource::removeDataFromDisk()
{
removeFromDisk(mResourceInstanceIdentifier);
}
void GenericResource::removeFromDisk(const QByteArray &instanceIdentifier)
{
Sink::Storage(Sink::storageLocation(), instanceIdentifier, Sink::Storage::ReadWrite).removeFromDisk();
Sink::Storage(Sink::storageLocation(), instanceIdentifier + ".userqueue", Sink::Storage::ReadWrite).removeFromDisk();
Sink::Storage(Sink::storageLocation(), instanceIdentifier + ".synchronizerqueue", Sink::Storage::ReadWrite).removeFromDisk();
Sink::Storage(Sink::storageLocation(), instanceIdentifier + ".changereplay", Sink::Storage::ReadWrite).removeFromDisk();
Sink::Storage(Sink::storageLocation(), instanceIdentifier + ".synchronization", Sink::Storage::ReadWrite).removeFromDisk();
}
qint64 GenericResource::diskUsage(const QByteArray &instanceIdentifier)
{
auto size = Sink::Storage(Sink::storageLocation(), instanceIdentifier, Sink::Storage::ReadOnly).diskUsage();
size += Sink::Storage(Sink::storageLocation(), instanceIdentifier + ".userqueue", Sink::Storage::ReadOnly).diskUsage();
size += Sink::Storage(Sink::storageLocation(), instanceIdentifier + ".synchronizerqueue", Sink::Storage::ReadOnly).diskUsage();
size += Sink::Storage(Sink::storageLocation(), instanceIdentifier + ".changereplay", Sink::Storage::ReadOnly).diskUsage();
return size;
}
void GenericResource::onProcessorError(int errorCode, const QString &errorMessage)
{
Warning() << "Received error from Processor: " << errorCode << errorMessage;
mError = errorCode;
}
int GenericResource::error() const
{
return mError;
}
void GenericResource::enqueueCommand(MessageQueue &mq, int commandId, const QByteArray &data)
{
flatbuffers::FlatBufferBuilder fbb;
auto commandData = Sink::EntityBuffer::appendAsVector(fbb, data.constData(), data.size());
auto buffer = Sink::CreateQueuedCommand(fbb, commandId, commandData);
Sink::FinishQueuedCommandBuffer(fbb, buffer);
mq.enqueue(fbb.GetBufferPointer(), fbb.GetSize());
}
void GenericResource::processCommand(int commandId, const QByteArray &data)
{
static int modifications = 0;
mUserQueue.startTransaction();
enqueueCommand(mUserQueue, commandId, data);
modifications++;
if (modifications >= sBatchSize) {
mUserQueue.commit();
modifications = 0;
mCommitQueueTimer.stop();
} else {
mCommitQueueTimer.start();
}
}
KAsync::Job<void> GenericResource::synchronizeWithSource()
{
return KAsync::start<void>([this](KAsync::Future<void> &future) {
Log() << " Synchronizing";
// Changereplay would deadlock otherwise when trying to open the synchronization store
enableChangeReplay(false);
mSynchronizer->synchronize()
.then<void>([this, &future]() {
Log() << "Done Synchronizing";
enableChangeReplay(true);
future.setFinished();
}, [this, &future](int errorCode, const QString &error) {
enableChangeReplay(true);
future.setError(errorCode, error);
})
.exec();
});
}
static void waitForDrained(KAsync::Future<void> &f, MessageQueue &queue)
{
if (queue.isEmpty()) {
f.setFinished();
} else {
QObject::connect(&queue, &MessageQueue::drained, [&f]() { f.setFinished(); });
}
};
KAsync::Job<void> GenericResource::processAllMessages()
{
// We have to wait for all items to be processed to ensure the synced items are available when a query gets executed.
// TODO: report errors while processing sync?
// TODO JOBAPI: A helper that waits for n events and then continues?
return KAsync::start<void>([this](KAsync::Future<void> &f) {
if (mCommitQueueTimer.isActive()) {
auto context = new QObject;
QObject::connect(&mCommitQueueTimer, &QTimer::timeout, context, [&f, context]() {
delete context;
f.setFinished();
});
} else {
f.setFinished();
}
})
.then<void>([this](KAsync::Future<void> &f) { waitForDrained(f, mSynchronizerQueue); })
.then<void>([this](KAsync::Future<void> &f) { waitForDrained(f, mUserQueue); })
.then<void>([this](KAsync::Future<void> &f) {
if (mChangeReplay->allChangesReplayed()) {
f.setFinished();
} else {
auto context = new QObject;
QObject::connect(mChangeReplay.data(), &ChangeReplay::changesReplayed, context, [&f, context]() {
delete context;
f.setFinished();
});
}
});
}
void GenericResource::updateLowerBoundRevision()
{
mProcessor->setOldestUsedRevision(qMin(mClientLowerBoundRevision, mChangeReplay->getLastReplayedRevision()));
}
void GenericResource::setLowerBoundRevision(qint64 revision)
{
mClientLowerBoundRevision = revision;
updateLowerBoundRevision();
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundefined-reinterpret-cast"
#include "genericresource.moc"
#pragma clang diagnostic pop
|