fabric/moduleworker.h

fabric/moduleworker.h

fabric/moduleworker.h

Namespaces

Name
Syntalos
Syntalos::detail

Classes

Name
classSyntalos::LiveValue
A value that the main thread can change while a worker is running.
classSyntalos::Guarded
A mutex-protected value that is handed over between the main thread and a worker.
classSyntalos::MainCallback
A callback that a worker can invoke from its thread, to run code on the main thread.
classSyntalos::WorkerContext
Thread-safe link from a worker to the module it belongs to.
structSyntalos::detail::WorkerTimerState
Connection between a WorkerTimer handle and the event loop that runs the timer.
classSyntalos::WorkerTimer
A one-shot timer of an event-driven worker.
classSyntalos::WorkerEvents
Event registrations of an event-driven worker.
structSyntalos::WorkerEvents::DataEvent
structSyntalos::WorkerEvents::TimedEvent
structSyntalos::WorkerEvents::OneShotEvent
classSyntalos::detail::WorkerHolderBase
Type-erased owner of a module worker.
classSyntalos::detail::WorkerHolder

Source code

/*
 * Copyright (C) 2019-2026 Matthias Klumpp <matthias@tenstral.net>
 *
 * Licensed under the GNU Lesser General Public License Version 3
 *
 * This program 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 3 of the license, or
 * (at your option) any later version.
 *
 * This software 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 software.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <QObject>
#include <QString>
#include <atomic>
#include <concepts>
#include <expected>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>

#include "datactl/datatypes.h"
#include "datactl/syclock.h"
#include "logging.h"
#include "streams/stream.h"

namespace Syntalos
{

class AbstractModule;
class MLinkModule;

template<typename T>
class LiveValue
{
public:
    LiveValue()
        : d(std::make_shared<Data>())
    {
    }

    LiveValue(T initialValue)
        : d(std::make_shared<Data>())
    {
        d->value = std::move(initialValue);
    }

    void set(T value)
    {
        const std::lock_guard<std::mutex> lock(d->mutex);
        d->value = std::move(value);
        d->changed.store(true, std::memory_order_release);
    }

    [[nodiscard]] T get() const
    {
        const std::lock_guard<std::mutex> lock(d->mutex);
        return d->value;
    }

    [[nodiscard]] std::optional<T> takeIfChanged()
    {
        if (!d->changed.load(std::memory_order_acquire))
            return std::nullopt;

        const std::lock_guard<std::mutex> lock(d->mutex);
        d->changed.store(false, std::memory_order_release);
        return d->value;
    }

private:
    struct Data {
        mutable std::mutex mutex;
        T value{};
        std::atomic_bool changed{false};
    };
    std::shared_ptr<Data> d;
};

template<typename T>
class Guarded
{
public:
    Guarded()
        : d(std::make_shared<Data>())
    {
    }

    Guarded(T initialValue)
        : d(std::make_shared<Data>())
    {
        d->value = std::move(initialValue);
    }

    void set(T value)
    {
        const std::lock_guard<std::mutex> lock(d->mutex);
        d->value = std::move(value);
    }

    [[nodiscard]] T take()
    {
        const std::lock_guard<std::mutex> lock(d->mutex);
        return std::exchange(d->value, T{});
    }

private:
    struct Data {
        std::mutex mutex;
        T value{};
    };
    std::shared_ptr<Data> d;
};

template<typename... Args>
class MainCallback
{
public:
    MainCallback() = default;

    MainCallback(QObject *context, std::function<void(const Args &...)> fn)
        : d(std::make_shared<Data>(context, std::move(fn)))
    {
    }

    void operator()(Args... args) const
    {
        if (!d)
            return;
        QMetaObject::invokeMethod(
            d->context,
            [d = this->d, argTuple = std::make_tuple(std::move(args)...)]() {
                std::apply(d->fn, argTuple);
            },
            Qt::QueuedConnection);
    }

    explicit operator bool() const
    {
        return d != nullptr;
    }

private:
    struct Data {
        Data(QObject *ctx, std::function<void(const Args &...)> f)
            : context(ctx),
              fn(std::move(f))
        {
        }

        QObject *context;
        std::function<void(const Args &...)> fn;
    };
    std::shared_ptr<const Data> d;
};

class Q_DECL_EXPORT WorkerContext
{
public:
    WorkerContext() = default;

    QuillLogger *log = nullptr;

    std::shared_ptr<SyncTimer> timer;

    [[nodiscard]] bool running() const
    {
        return m_running != nullptr && m_running->load();
    }

    void waitForStart() const;

    void raiseError(const QString &message) const;
    void raiseError(const std::string &message) const;
    void raiseError(const char *message) const;

    void setStatusMessage(const QString &message) const;
    void setStatusMessage(const std::string &message) const;
    void setStatusMessage(const char *message) const;

    void setStateDormant() const;

    void setStateReady() const;

    [[nodiscard]] QString moduleName() const
    {
        return m_modName;
    }

private:
    friend class AbstractModule;
    friend class MLinkModule;

    AbstractModule *m_mod = nullptr;
    const std::atomic_bool *m_running = nullptr;
    QString m_modName;
};

namespace detail
{

struct WorkerTimerState {
    std::mutex mutex;

    std::function<void(std::int64_t)> arm;
};

} // namespace detail

class Q_DECL_EXPORT WorkerTimer
{
public:
    WorkerTimer() = default;

    void start(const milliseconds_t &delay) const;
    void start(const microseconds_t &delay) const;

    void stop() const;

private:
    friend class WorkerEvents;
    std::shared_ptr<detail::WorkerTimerState> d;
};

using WorkerTimedEventFn = std::function<void(int &)>;

using WorkerDataEventFn = std::function<void()>;

class WorkerEvents
{
public:
    struct DataEvent {
        std::shared_ptr<VariantStreamSubscription> subscription;
        WorkerDataEventFn fn;
    };

    struct TimedEvent {
        int intervalMsec;
        WorkerTimedEventFn fn;
    };

    struct OneShotEvent {
        std::shared_ptr<detail::WorkerTimerState> timer;
        WorkerDataEventFn fn;
    };

    template<typename Fn>
        requires std::invocable<Fn &>
    void onData(std::shared_ptr<VariantStreamSubscription> subscription, Fn &&fn)
    {
        m_dataEvents.push_back(DataEvent{std::move(subscription), WorkerDataEventFn(std::forward<Fn>(fn))});
    }

    template<typename Fn>
        requires std::invocable<Fn &, int &>
    void every(const milliseconds_t &interval, Fn &&fn)
    {
        m_timedEvents.push_back(
            TimedEvent{static_cast<int>(interval.count()), WorkerTimedEventFn(std::forward<Fn>(fn))});
    }

    template<typename Fn>
        requires std::invocable<Fn &>
    [[nodiscard]] WorkerTimer timer(Fn &&fn)
    {
        WorkerTimer timer;
        timer.d = std::make_shared<detail::WorkerTimerState>();
        m_oneShotEvents.push_back(OneShotEvent{timer.d, WorkerDataEventFn(std::forward<Fn>(fn))});
        return timer;
    }

    [[nodiscard]] const std::vector<DataEvent> &dataEvents() const
    {
        return m_dataEvents;
    }

    [[nodiscard]] const std::vector<TimedEvent> &timedEvents() const
    {
        return m_timedEvents;
    }

    [[nodiscard]] const std::vector<OneShotEvent> &oneShotEvents() const
    {
        return m_oneShotEvents;
    }

private:
    std::vector<DataEvent> m_dataEvents;
    std::vector<TimedEvent> m_timedEvents;
    std::vector<OneShotEvent> m_oneShotEvents;
};

template<typename W>
concept ThreadWorker = requires(W &w) { w.run(); };

template<typename W>
concept EventWorker = requires(W &w, WorkerEvents &ev) { w.setup(ev); };

template<typename W>
concept WorkerDeclared = requires(W &w) {
    { w.mod } -> std::same_as<WorkerContext &>;
};

namespace detail
{

inline QString workerErrorToString(const QString &error)
{
    return error;
}

inline QString workerErrorToString(const std::string &error)
{
    return QString::fromStdString(error);
}

inline QString workerErrorToString(const char *error)
{
    return QString::fromUtf8(error);
}

class Q_DECL_EXPORT WorkerHolderBase
{
public:
    WorkerHolderBase() = default;
    virtual ~WorkerHolderBase();

    [[nodiscard]] virtual bool isThreadWorker() const = 0;

    virtual std::expected<void, QString> run() = 0;

    [[nodiscard]] const WorkerEvents &events() const
    {
        return m_events;
    }

protected:
    WorkerEvents m_events;

private:
    Q_DISABLE_COPY(WorkerHolderBase)
};

template<typename W>
class WorkerHolder final : public WorkerHolderBase
{
public:
    explicit WorkerHolder(W &&w)
        : worker(std::move(w))
    {
    }

    [[nodiscard]] bool isThreadWorker() const override
    {
        return ThreadWorker<W>;
    }

    std::expected<void, QString> run() override
    {
        if constexpr (ThreadWorker<W>) {
            if constexpr (std::is_void_v<decltype(worker.run())>) {
                worker.run();
            } else {
                auto res = worker.run();
                if (!res.has_value())
                    return std::unexpected(workerErrorToString(res.error()));
            }
        }
        return {};
    }

    void setupEvents()
    {
        if constexpr (EventWorker<W>)
            worker.setup(m_events);
    }

    W worker;
};

} // namespace detail

} // namespace Syntalos

Updated on 2026-11-26 at 18:54:14 +0000