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