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
|
#include "messagequeue.h"
#include "storage.h"
#include <QDebug>
MessageQueue::MessageQueue(const QString &storageRoot, const QString &name)
: mStorage(storageRoot, name, Akonadi2::Storage::ReadWrite)
{
}
void MessageQueue::enqueue(void const *msg, size_t size)
{
mStorage.startTransaction(Akonadi2::Storage::ReadWrite);
const qint64 revision = mStorage.maxRevision() + 1;
const QByteArray key = QString("%1").arg(revision).toUtf8();
mStorage.write(key.data(), key.size(), msg, size);
mStorage.setMaxRevision(revision);
mStorage.commitTransaction();
emit messageReady();
}
void MessageQueue::dequeue(const std::function<void(void *ptr, int size, std::function<void(bool success)>)> &resultHandler,
const std::function<void(const Error &error)> &errorHandler)
{
bool readValue = false;
mStorage.scan("", [this, resultHandler, errorHandler, &readValue](void *keyPtr, int keySize, void *valuePtr, int valueSize) -> bool {
const auto key = QByteArray::fromRawData(static_cast<char*>(keyPtr), keySize);
if (Akonadi2::Storage::isInternalKey(key)) {
return true;
}
readValue = true;
resultHandler(valuePtr, valueSize, [this, key, errorHandler](bool success) {
if (success) {
mStorage.remove(key.data(), key.size(), [errorHandler](const Akonadi2::Storage::Error &error) {
qDebug() << "Error while removing value" << error.message;
errorHandler(Error(error.store, error.code, "Error while removing value: " + error.message));
});
if (isEmpty()) {
emit this->drained();
}
} else {
//TODO re-enqueue?
}
});
return false;
},
[errorHandler](const Akonadi2::Storage::Error &error) {
qDebug() << "Error while retrieving value" << error.message;
errorHandler(Error(error.store, error.code, error.message));
}
);
if (!readValue) {
errorHandler(Error("messagequeue", -1, "No message found"));
}
}
bool MessageQueue::isEmpty()
{
int count = 0;
mStorage.scan("", [&count](void *keyPtr, int keySize, void *valuePtr, int valueSize) -> bool {
const auto key = QByteArray::fromRawData(static_cast<char*>(keyPtr), keySize);
if (!Akonadi2::Storage::isInternalKey(key)) {
count++;
return false;
}
return true;
},
[](const Akonadi2::Storage::Error &error) {
qDebug() << "Error while checking if empty" << error.message;
});
return count == 0;
}
|