Back to Site
Loading...
Searching...
No Matches
message_json.h
Go to the documentation of this file.
1#pragma once
2
30#include "node/peer_network.h"
31#include "peer/peer.h"
32#include "peer/peer_id.h"
33#include "core/bytes.h"
34#include "util/json.h"
35
36#include <functional>
37#include <mutex>
38#include <string>
39#include <unordered_map>
40#include <vector>
41
42namespace librats {
43
44class MessageJson final : public Subsystem {
45public:
46 using Handler = std::function<void(const PeerId& from, const librats::Json& data)>;
47 using SendCallback = std::function<void(bool ok, const std::string& error)>;
48
51 void on(const std::string& type, Handler handler);
52
54 void once(const std::string& type, Handler handler);
55
57 void off(const std::string& type);
58
61 void send(const std::string& type, const librats::Json& data, SendCallback cb = nullptr);
62
65 void send(const PeerId& to, const std::string& type, const librats::Json& data,
66 SendCallback cb = nullptr);
67
68 // Subsystem — no background thread; purely event-driven.
69 void attach(NodeContext& ctx) override;
70 void start() override {}
71 void stop() override {}
72
73private:
74 void on_typed(const PeerId& from, ByteView payload);
75 static Bytes encode(const std::string& type, const librats::Json& data);
76
77 struct Entry {
78 Handler handler;
79 bool once;
80 };
81
82 PeerNetwork* network_ = nullptr;
83 mutable std::mutex mutex_;
84 std::unordered_map<std::string, std::vector<Entry>> handlers_;
85};
86
87} // namespace librats
void attach(NodeContext &ctx) override
void on(const std::string &type, Handler handler)
Register a handler for type.
void once(const std::string &type, Handler handler)
Like on(), but the handler is removed right after it fires once.
void send(const PeerId &to, const std::string &type, const librats::Json &data, SendCallback cb=nullptr)
Send data of type to one peer.
std::function< void(bool ok, const std::string &error)> SendCallback
void send(const std::string &type, const librats::Json &data, SendCallback cb=nullptr)
Broadcast data of type to all connected peers.
void stop() override
std::function< void(const PeerId &from, const librats::Json &data)> Handler
void start() override
void off(const std::string &type)
Remove every handler registered for type.
A pluggable network subsystem.
Definition node.h:65
A lightweight handle to a connected peer.
Self-certifying peer identity.
The narrow contract a subsystem needs from the node — and nothing more.