Fray Engine
Loading...
Searching...
No Matches
message.hpp
Go to the documentation of this file.
1/* message.hpp */
2
3#ifndef _FRAY_MESSAGE_HPP_
4#define _FRAY_MESSAGE_HPP_
5
6#include <algorithm>
7#include <array>
8#include <atomic>
9#include <chrono>
10#include <cstddef>
11#include <cstdint>
12#include <limits>
13#include <memory>
14#include <optional>
15#include <set>
16#include <string>
17#include <vector>
18
19#include "errors.hpp"
20#include "fray.pb.h"
21#include "types.hpp"
22#include "uid.hpp"
23
29namespace fray
30{
31 namespace message
32 {
34 constexpr F_uchar PREFIX_VERSION = 0;
36 constexpr std::uint32_t PROTOCOL_VERSION = 0;
38 constexpr std::uint32_t LOADING_WINDOW_ID = 0;
40 constexpr std::uint32_t MAIN_WINDOW_ID = 1;
42 constexpr size_t PREFIX_SIZE = 40;
44 constexpr F_ulong MAX_FRAME_LENGTH = 16 * 1024 * 1024;
45
52 struct Prefix
53 {
57 ProcessKind destinationKind = PROCESS_KIND_UNSPECIFIED;
61 ProcessKind senderKind = PROCESS_KIND_UNSPECIFIED;
66 F_ulong length = 0; // Bytes after the prefix (header + payload)
72 MessageCategory category = MESSAGE_CATEGORY_COMMAND;
73 };
74
81 inline bool isCommand(
82 const Prefix& prefix,
83 F_ulong id)
84 {
85 return prefix.category == MESSAGE_CATEGORY_COMMAND && prefix.operationId == id;
86 }
87
94 inline bool isNotice(
95 const Prefix& prefix,
96 F_ulong id)
97 {
98 return prefix.category == MESSAGE_CATEGORY_MESSAGE && prefix.operationId == id;
99 }
100
106 inline bool isControl(
107 const Prefix& prefix)
108 {
109 return isNotice(prefix, MSG_READY) || isCommand(prefix, COMMAND_REQUEST_READY) ||
110 isCommand(prefix, COMMAND_PING) || isCommand(prefix, COMMAND_PONG);
111 }
112
119 inline bool isConsoleCommand(
120 const Prefix& prefix)
121 {
122 return prefix.category == MESSAGE_CATEGORY_COMMAND && !isControl(prefix) &&
123 prefix.operationId != COMMAND_LOG_ENTRY && prefix.operationId != COMMAND_LOG_PAGE_REQUEST &&
124 prefix.operationId != COMMAND_LOG_PAGE &&
125 prefix.operationId != COMMAND_CONSOLE_ADD && prefix.operationId != COMMAND_CONSOLE_UPDATE &&
126 prefix.operationId != COMMAND_NOTIFY;
127 }
128
134 inline bool wantsLog(
135 std::uint32_t flags)
136 {
137 return (flags & MESSAGE_FLAG_NO_LOG) == 0;
138 }
139
145 inline bool wantsConsole(
146 std::uint32_t flags)
147 {
148 return (flags & MESSAGE_FLAG_NO_CONSOLE) == 0;
149 }
150
157 inline bool isTracked(
158 const Prefix& prefix,
159 std::uint32_t flags)
160 {
161 return isConsoleCommand(prefix) && (wantsLog(flags) || wantsConsole(flags));
162 }
163
168 struct InData
169 {
173 Header header;
175 std::shared_ptr<const std::vector<F_uchar>> frame;
176
178 const F_uchar *payload() const { return frame->data() + PREFIX_SIZE + prefix.headerLength; }
180 size_t payloadSize() const { return prefix.length - prefix.headerLength; }
181 };
182
184 namespace detail
185 {
191 inline void put32(
192 F_uchar *out,
193 F_ulong v)
194 {
195 out[0] = static_cast<F_uchar>(v >> 24);
196 out[1] = static_cast<F_uchar>(v >> 16);
197 out[2] = static_cast<F_uchar>(v >> 8);
198 out[3] = static_cast<F_uchar>(v);
199 }
200
207 const F_uchar *in)
208 {
209 return (static_cast<F_ulong>(in[0]) << 24) | (static_cast<F_ulong>(in[1]) << 16) |
210 (static_cast<F_ulong>(in[2]) << 8) | static_cast<F_ulong>(in[3]);
211 }
212 }
213
219 inline void encodePrefix(
220 const Prefix &p,
221 F_uchar *out)
222 {
223 out[0] = p.version;
224 out[1] = static_cast<F_uchar>(p.destinationKind);
225 detail::put32(out + 2, p.destinationId);
226 out[6] = static_cast<F_uchar>(p.senderKind);
227 detail::put32(out + 7, p.senderId);
228 detail::put32(out + 11, p.operationId);
229 detail::put32(out + 15, p.length);
230 detail::put32(out + 19, p.headerLength);
231 std::copy(p.uid.begin(), p.uid.end(), out + 23);
232 out[39] = static_cast<F_uchar>(p.category);
233 }
234
244 const F_uchar *data,
245 size_t size,
246 Prefix &out)
247 {
248 if (size < PREFIX_SIZE)
249 return errors::INVALID_MESSAGE;
250 if (data[0] != PREFIX_VERSION)
251 return errors::UNSUPPORTED_MESSAGE_VERSION;
252
253 Prefix p;
254 p.version = data[0];
255 p.destinationKind = static_cast<ProcessKind>(data[1]);
256 p.destinationId = detail::get32(data + 2);
257 p.senderKind = static_cast<ProcessKind>(data[6]);
258 p.senderId = detail::get32(data + 7);
259 p.operationId = detail::get32(data + 11);
260 p.length = detail::get32(data + 15);
261 p.headerLength = detail::get32(data + 19);
262 std::copy(data + 23, data + 39, p.uid.begin());
263 if (!MessageCategory_IsValid(data[39]))
264 return errors::INVALID_MESSAGE;
265 p.category = static_cast<MessageCategory>(data[39]);
266 if (p.headerLength > p.length)
267 return errors::INVALID_MESSAGE;
268 if (p.length > MAX_FRAME_LENGTH)
269 return errors::MESSAGE_TOO_LARGE;
270
271 out = p;
272 return errors::NONE;
273 }
274
282 inline std::shared_ptr<const std::vector<F_uchar>> assignUid(
283 const std::shared_ptr<const std::vector<F_uchar>>& frame,
284 Prefix& prefix)
285 {
286 if (std::any_of(prefix.uid.begin(), prefix.uid.end(), [](F_uchar byte) { return byte != 0; }))
287 return frame;
288 const auto uid = identity::generate();
289 auto assigned = std::make_shared<std::vector<F_uchar>>(*frame);
290 std::copy(uid.begin(), uid.end(), prefix.uid.begin());
291 std::copy(prefix.uid.begin(), prefix.uid.end(), assigned->begin() + 23);
292 return assigned;
293 }
294
307 Prefix prefix,
308 const Header &header,
309 const F_uchar *payload,
310 size_t payloadSize,
311 std::vector<F_uchar> &out)
312 {
313 const size_t headerSize = header.ByteSizeLong();
314 if (header.protocol_version() != PROTOCOL_VERSION)
315 return errors::UNSUPPORTED_MESSAGE_VERSION;
316 if (!MessageCategory_IsValid(prefix.category) ||
317 headerSize > static_cast<size_t>(std::numeric_limits<int>::max()) ||
318 payloadSize > UINT32_MAX - headerSize || (payloadSize && !payload))
319 return errors::INVALID_MESSAGE;
320 if (headerSize + payloadSize > MAX_FRAME_LENGTH)
321 return errors::MESSAGE_TOO_LARGE;
322
323 prefix.length = static_cast<F_ulong>(headerSize + payloadSize);
324 prefix.headerLength = static_cast<F_ulong>(headerSize);
325
326 std::vector<F_uchar> frame(PREFIX_SIZE + headerSize + payloadSize);
327 encodePrefix(prefix, frame.data());
328 if (!header.SerializeToArray(frame.data() + PREFIX_SIZE, static_cast<int>(headerSize)))
329 return errors::INVALID_MESSAGE;
330 if (payloadSize > 0)
331 std::copy(payload, payload + payloadSize, frame.begin() + PREFIX_SIZE + headerSize);
332
333 out = std::move(frame);
334 return errors::NONE;
335 }
336
342 inline const char *processName(
343 ProcessKind kind)
344 {
345 switch (kind)
346 {
347 case PROCESS_KIND_ENGINE: return "Engine";
348 case PROCESS_KIND_ENGINE_PLUGIN: return "Engine Plugin";
349 case PROCESS_KIND_ELECTRON_MAIN: return "Electron Main";
350 case PROCESS_KIND_ELECTRON_RENDERER: return "Electron Renderer";
351 case PROCESS_KIND_ELECTRON_PLUGIN: return "Electron Plugin";
352 case PROCESS_KIND_BROADCAST: return "Everyone";
353 case PROCESS_KIND_MULTICAST: return "Multiple recipients";
354 default: return "Unknown";
355 }
356 }
357
364 inline std::string processInstanceName(
365 ProcessKind kind,
366 std::uint32_t id)
367 {
368 std::string name = processName(kind);
369 if (kind == PROCESS_KIND_ELECTRON_RENDERER)
370 {
371 name += " " + std::to_string(id);
372 if (id == LOADING_WINDOW_ID) name += " (Loading)";
373 else if (id == MAIN_WINDOW_ID) name += " (Main window)";
374 }
375 else if (kind == PROCESS_KIND_ENGINE_PLUGIN || kind == PROCESS_KIND_ELECTRON_PLUGIN)
376 name += " " + std::to_string(id);
377 return name;
378 }
379
385 inline uint64_t nextMessageId()
386 {
387 static std::atomic<uint64_t> next{1};
388 return next.fetch_add(1);
389 }
390
392 constexpr std::uint32_t SILENT_FLAGS = MESSAGE_FLAG_NO_LOG | MESSAGE_FLAG_NO_CONSOLE;
393
398 {
400 ProcessKind destination = PROCESS_KIND_UNSPECIFIED;
406 std::string payload;
408 PayloadType payloadType = PAYLOAD_TYPE_NONE;
410 MessageType messageType = MESSAGE_TYPE_NONE;
412 std::optional<std::string> targetProject;
414 uint32_t ttlMs = 0;
416 MessageCategory category = MESSAGE_CATEGORY_COMMAND;
421 std::uint32_t flags = 0;
423 std::vector<std::pair<ProcessKind, F_ulong>> recipients;
424 };
425
432 const Header& header)
433 {
434 if (header.recipients().empty())
435 return false;
436 std::set<std::pair<ProcessKind, F_ulong>> seen;
437 for (const auto& recipient : header.recipients())
438 {
439 if (recipient.kind() < PROCESS_KIND_ENGINE || recipient.kind() > PROCESS_KIND_ELECTRON_PLUGIN ||
440 !seen.emplace(recipient.kind(), recipient.id()).second)
441 return false;
442 }
443 return true;
444 }
445
451 {
452 public:
461 const FrameOptions &options,
462 std::shared_ptr<const std::vector<F_uchar>> &out) const
463 {
464 if (!options.payload.empty() && options.payloadType == PAYLOAD_TYPE_NONE)
465 return errors::INVALID_MESSAGE;
466 Prefix prefix;
467 prefix.destinationKind = options.destination;
468 prefix.destinationId = options.destinationId;
469 prefix.senderKind = PROCESS_KIND_ENGINE;
470 prefix.operationId = options.operation;
471 prefix.category = options.category;
472 Header header;
473 header.set_protocol_version(PROTOCOL_VERSION);
474 header.set_message_id(nextMessageId());
475 header.set_timestamp(std::chrono::duration_cast<std::chrono::milliseconds>(
476 std::chrono::system_clock::now().time_since_epoch()).count());
477 header.set_sender_name(processName(PROCESS_KIND_ENGINE));
478 header.set_destination_name(processName(options.destination));
479 header.set_payload_type(options.payloadType);
480 header.set_message_type(options.messageType);
481 if (options.targetProject) header.set_target_project(*options.targetProject);
482 header.set_ttl_ms(options.ttlMs);
483 header.set_flags(options.flags);
484 for (const auto& recipient : options.recipients)
485 {
486 auto* target = header.add_recipients();
487 target->set_kind(recipient.first);
488 target->set_id(recipient.second);
489 }
490 if (options.destination == PROCESS_KIND_MULTICAST
491 ? options.destinationId != 0 || !validMulticastRecipients(header)
492 : !options.recipients.empty())
493 return errors::INVALID_MESSAGE;
494 auto frame = std::make_shared<std::vector<F_uchar>>();
495 const F_err err = buildFrame(prefix, header, reinterpret_cast<const F_uchar *>(options.payload.data()),
496 options.payload.size(), *frame);
497 if (err != errors::NONE)
498 return err;
499 out = std::move(frame);
500 return errors::NONE;
501 }
502 };
503
512 std::shared_ptr<const std::vector<F_uchar>> frame,
513 InData &out)
514 {
515 if (!frame)
516 return errors::INVALID_MESSAGE;
517
518 InData in;
519 if (F_err err = decodePrefix(frame->data(), frame->size(), in.prefix))
520 return err;
521 if (frame->size() != PREFIX_SIZE + static_cast<size_t>(in.prefix.length))
522 return errors::INVALID_MESSAGE;
523 if (in.prefix.headerLength > static_cast<F_ulong>(std::numeric_limits<int>::max()))
524 return errors::INVALID_MESSAGE;
525 if (!in.header.ParseFromArray(frame->data() + PREFIX_SIZE, static_cast<int>(in.prefix.headerLength)))
526 return errors::INVALID_MESSAGE;
527 if (in.header.protocol_version() != PROTOCOL_VERSION)
528 return errors::UNSUPPORTED_MESSAGE_VERSION;
529
530 in.frame = std::move(frame);
531 out = std::move(in);
532 return errors::NONE;
533 }
534 }
535}
536
537#endif
Builds outgoing frames sent by the Engine (sender is always the Engine). Stateless; safe to use from ...
Definition message.hpp:451
F_err build(const FrameOptions &options, std::shared_ptr< const std::vector< F_uchar > > &out) const
Builds an Engine frame from the options, stamping the protocol version, a new message id and the curr...
Definition message.hpp:460
F_long F_err
Error return type used across the Engine; the value is a fray::errors::code (0 / NONE means success).
Definition errors.hpp:13
std::array< std::uint8_t, 16 > Uid
A 128-bit identifier shared by routing and stored entries.
Definition uid.hpp:18
Uid generate()
Generates a random, globally unique identifier.
Definition uid.hpp:24
Internal helpers for big-endian encoding.
Definition message.hpp:185
void put32(F_uchar *out, F_ulong v)
Writes a 32-bit value as 4 big-endian bytes.
Definition message.hpp:191
F_ulong get32(const F_uchar *in)
Reads 4 big-endian bytes as a 32-bit value.
Definition message.hpp:206
bool isCommand(const Prefix &prefix, F_ulong id)
Tests whether a prefix identifies a command.
Definition message.hpp:81
F_err decodePrefix(const F_uchar *data, size_t size, Prefix &out)
Parses and validates a prefix from received bytes.
Definition message.hpp:243
const char * processName(ProcessKind kind)
Human-readable name of a process kind, also used as the header sender/destination name.
Definition message.hpp:342
bool wantsLog(std::uint32_t flags)
Tests whether a message's header flags leave it in the disk log.
Definition message.hpp:134
F_err parseFrame(std::shared_ptr< const std::vector< F_uchar > > frame, InData &out)
Parses the header of a complete frame. The payload is not read or copied.
Definition message.hpp:511
uint64_t nextMessageId()
Returns the next message ID. Message IDs are unique per sender, so every engine message takes its ID ...
Definition message.hpp:385
constexpr F_ulong MAX_FRAME_LENGTH
Largest allowed value of the prefix length field (header + payload). Checked before any buffer is all...
Definition message.hpp:44
std::shared_ptr< const std::vector< F_uchar > > assignUid(const std::shared_ptr< const std::vector< F_uchar > > &frame, Prefix &prefix)
Assigns a random 128-bit UID to a frame whose prefix does not have one. Existing UIDs are preserved; ...
Definition message.hpp:282
bool wantsConsole(std::uint32_t flags)
Tests whether a message's header flags leave it in the Console.
Definition message.hpp:145
F_err buildFrame(Prefix prefix, const Header &header, const F_uchar *payload, size_t payloadSize, std::vector< F_uchar > &out)
Builds a complete frame (prefix + protobuf header + payload) into a byte vector. The prefix's length ...
Definition message.hpp:306
constexpr std::uint32_t SILENT_FLAGS
Definition message.hpp:392
bool validMulticastRecipients(const Header &header)
Validates the explicit destinations of a multicast header.
Definition message.hpp:431
constexpr std::uint32_t PROTOCOL_VERSION
Version written to the protobuf message header.
Definition message.hpp:36
bool isControl(const Prefix &prefix)
Identifies readiness and health control frames.
Definition message.hpp:106
constexpr std::uint32_t MAIN_WINDOW_ID
Renderer instance ID assigned to the first application window.
Definition message.hpp:40
bool isConsoleCommand(const Prefix &prefix)
Identifies commands the Console shows as entries. Control traffic and the Console's own log and entry...
Definition message.hpp:119
constexpr size_t PREFIX_SIZE
Size in bytes of the fixed binary routing prefix.
Definition message.hpp:42
constexpr std::uint32_t LOADING_WINDOW_ID
Renderer instance ID assigned to the loading window.
Definition message.hpp:38
constexpr F_uchar PREFIX_VERSION
Wire format version written to, and required in, byte 0 of every prefix.
Definition message.hpp:34
std::string processInstanceName(ProcessKind kind, std::uint32_t id)
Names a process instance for readiness diagnostics.
Definition message.hpp:364
bool isTracked(const Prefix &prefix, std::uint32_t flags)
Identifies messages the Engine router logs, shows in the Console, or both.
Definition message.hpp:157
bool isNotice(const Prefix &prefix, F_ulong id)
Tests whether a prefix identifies a protocol notification.
Definition message.hpp:94
void encodePrefix(const Prefix &p, F_uchar *out)
Serializes a prefix into its PREFIX_SIZE-byte big-endian wire form.
Definition message.hpp:219
Everything FrameBuilder needs to build one outgoing Engine message.
Definition message.hpp:398
std::optional< std::string > targetProject
Definition message.hpp:412
std::vector< std::pair< ProcessKind, F_ulong > > recipients
Definition message.hpp:423
MessageCategory category
Definition message.hpp:416
A parsed incoming message. The payload is a view into the frame, which this keeps alive via shared ow...
Definition message.hpp:169
size_t payloadSize() const
Payload length in bytes (prefix.length minus headerLength).
Definition message.hpp:180
std::shared_ptr< const std::vector< F_uchar > > frame
Definition message.hpp:175
const F_uchar * payload() const
Pointer to the first payload byte inside frame (valid only while frame is held; frame must be non-nul...
Definition message.hpp:178
Fixed-size routing prefix at the start of every frame; routers read only this. All integers are big-e...
Definition message.hpp:53
ProcessKind destinationKind
Definition message.hpp:57
ProcessKind senderKind
Definition message.hpp:61
MessageCategory category
Definition message.hpp:72
identity::Uid uid
Definition message.hpp:70
unsigned char F_uchar
Alias for unsigned char (a byte).
Definition types.hpp:26
uint32_t F_ulong
Unsigned 32-bit integer.
Definition types.hpp:34