summaryrefslogtreecommitdiffstats
path: root/common/messagequeue.h
blob: a2b72261db4eebf0bd6b2e729fc1cb4bcc3f4ccf (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
#pragma once

#include "sink_export.h"
#include <QObject>
#include <QByteArrayList>
#include <string>
#include <functional>
#include <QString>
#include <KAsync/Async>
#include "storage.h"

/**
 * A persistent FIFO message queue.
 */
class SINK_EXPORT MessageQueue : public QObject
{
    Q_OBJECT
public:
    enum ErrorCodes
    {
        NoMessageFound
    };
    class Error
    {
    public:
        Error(const QByteArray &s, int c, const QByteArray &m) : store(s), message(m), code(c)
        {
        }
        QByteArray store;
        QByteArray message;
        int code;
    };

    MessageQueue(const QString &storageRoot, const QString &name);
    ~MessageQueue();

    void startTransaction();
    void enqueue(void const *msg, size_t size);
    void enqueue(const QByteArray &value);
    // Dequeue a message. This will return a new message everytime called.
    // Call the result handler with a success response to remove the message from the store.
    // TODO track processing progress to avoid processing the same message with the same preprocessor twice?
    void dequeue(const std::function<void(void *ptr, int size, std::function<void(bool success)>)> &resultHandler, const std::function<void(const Error &error)> &errorHandler);
    KAsync::Job<void> dequeueBatch(int maxBatchSize, const std::function<KAsync::Job<void>(const QByteArray &)> &resultHandler);
    bool isEmpty();

public slots:
    void commit();

signals:
    void messageReady();
    void drained();

private slots:
    void processRemovals();

private:
    Q_DISABLE_COPY(MessageQueue);
    Sink::Storage::DataStore mStorage;
    Sink::Storage::DataStore::Transaction mWriteTransaction;
    QByteArrayList mPendingRemoval;
};