Fray Engine
Loading...
Searching...
No Matches
ipc_manager.hpp
Go to the documentation of this file.
1/* ipc_manager.hpp */
2
3#ifndef _FRAY_IPC_MANAGER_HPP_
4#define _FRAY_IPC_MANAGER_HPP_
5
6#include <boost/asio.hpp>
7#include <array>
8#include <set>
9#include <vector>
10#include <algorithm>
11#include <atomic>
12#include <deque>
13#include <new>
14#include <stdexcept>
15#include <condition_variable>
16#include <functional>
17#include <map>
18#include <mutex>
19#include <limits>
20#include <string>
21#include "errors.hpp"
22#include "log_manager.hpp"
23#include "message.hpp"
24#include "message_router.hpp"
25#include "neighbor_monitor.hpp"
26#include "outgoing_router.hpp"
27#include "thread_manager.hpp"
28#include "types.hpp"
29#include "fray_manager.hpp"
30
31namespace fray
32{
33 namespace ipc
34 {
35
37 using Frame = std::shared_ptr<const std::vector<F_uchar>>;
39 using Socket = std::shared_ptr<boost::asio::ip::tcp::socket>;
41 using ConnectionHandler = std::function<void(Socket)>;
42
43 class IPCManager; // forward
44
50 class TCPServer : public std::enable_shared_from_this<TCPServer>
51 {
52 private:
54 boost::asio::ip::tcp::acceptor _acceptor;
62 boost::asio::steady_timer _drainTimer;
66 std::set<std::shared_ptr<boost::asio::ip::tcp::socket>> _sessions;
68 IPCManager *_manager = nullptr;
71 // Frames waiting to be written, per session. Only the network thread touches these.
72 std::map<std::shared_ptr<boost::asio::ip::tcp::socket>,
73 std::deque<Frame>> _outgoing;
74
76 F_void accept();
83 std::shared_ptr<boost::asio::ip::tcp::socket> session);
90 Socket session,
91 Frame frame);
97 std::shared_ptr<boost::asio::ip::tcp::socket> session);
103 Socket session);
106
107 public:
115 boost::asio::io_context &ctx,
117 IPCManager *manager)
118 : _acceptor(ctx, {boost::asio::ip::tcp::v4(), port}), _drainTimer(ctx),
119 _port(port),
120 _manager(manager)
121 {
122 // Port 0 asks the OS for a free port; read back the one it chose.
123 _port = _acceptor.local_endpoint().port();
124 fray::log::engineInfo("Constructed server on port %d.", _port);
125 }
126
129 {
130 fray::log::engineInfo("Destroyed TCPServer on port %d.", _port);
131 }
132
138 ConnectionHandler handler) { _connectionHandler = std::move(handler); }
139
145 F_void stop();
153 Frame frame);
161 Socket session,
162 Frame frame)
163 {
164 if (!session || !frame)
165 {
166 fray::log::engineError("Cannot send a message without a session and frame.");
167 return;
168 }
169 write(std::move(session), std::move(frame));
170 }
171
172 F_ushort port() const { return _port; }
173 };
174
176 using TCPServerSP = std::shared_ptr<TCPServer>;
177
186 {
187 private:
189 boost::asio::io_context _io;
191 boost::asio::steady_timer _monitorTimer{_io};
193 boost::asio::steady_timer _startupTimer{_io};
195 boost::asio::steady_timer _loadingIntroTimer{_io};
197 static constexpr auto loadingIntroDuration = std::chrono::milliseconds(2000);
199 std::atomic<bool> _loadingWindowActive{true};
201 bool _startupActive = false;
202 bool _startupFailed = false;
204 unsigned _startupMilestones = 0;
205 unsigned _startupPercent = 0;
213
214 static constexpr unsigned allStartupMilestones =
216 static constexpr unsigned startupMilestoneCount = 6;
220 std::function<std::vector<std::string>()> _fontReader = [] { return std::vector<std::string>(); };
222 std::vector<std::string> _systemFonts;
224 bool _systemFontsLoaded = false;
226 std::atomic<bool> _startupMainPending{false};
228 std::vector<TCPServerSP> _servers;
232 bool _started = false;
234 bool _waited = false;
236 bool _finished = false;
240 boost::asio::steady_timer _shutdownTimer{_io};
242 bool _shutdownPolling = false;
250 std::mutex _networkMutex;
252 std::condition_variable _networkWake;
254 bool _networkStopped = false;
256 uint64_t _heartbeat = 0;
258 uint64_t _processedCount = 0;
260 std::chrono::steady_clock::time_point _lastProgress = std::chrono::steady_clock::now();
264 using Neighbor = std::pair<ProcessKind, F_ulong>;
265 // Owned by the engine message thread, which is the router: nothing else may touch it.
269
274 [this](Neighbor neighbor, routing::MonitorCommand command)
275 {
276 const F_ulong id = command == routing::MonitorCommand::probe ? COMMAND_REQUEST_READY : COMMAND_PING;
277 if (command == routing::MonitorCommand::probe)
278 fray::log::engineInfo("Sending readiness probe to %s.", message::processInstanceName(neighbor.first, neighbor.second).c_str());
279 message::FrameOptions options{neighbor.first, id, neighbor.second};
281 sendBuilt(options);
282 },
283 [this](Neighbor neighbor) { return _outgoing.state(neighbor); },
284 [this](Neighbor neighbor, routing::NeighborState state)
285 {
287 {
288 const auto previous = _outgoing.state(neighbor);
289 if (_outgoing.markReady(neighbor) &&
291 previous == routing::NeighborState::down))
292 fray::log::engineInfo("%s recovered and is ready.", message::processInstanceName(neighbor.first, neighbor.second).c_str());
293 }
294 else
295 {
296 _outgoing.setState(neighbor, state);
298 {
299 if (!(neighbor.first == PROCESS_KIND_ELECTRON_MAIN && neighbor.second == 0 &&
300 _startupMainPending.load()))
301 _outgoing.discardQueue(neighbor);
302 if (neighbor.first == PROCESS_KIND_ELECTRON_MAIN && neighbor.second == 0)
303 _application.cancelPrompts("Electron Main is unavailable.");
304 }
306 const char *name = state == routing::NeighborState::suspect ? "SUSPECT" :
308 state == routing::NeighborState::down ? "DOWN" : "UNREACHABLE";
309 fray::log::engineWarn("%s is %s.", message::processName(neighbor.first), name);
310 }
311 }};
312 // Declared last so any threads it owns are joined before anything they use is destroyed.
314 std::unique_ptr<threads::ThreadManager> _ownedThreads;
317
318 public:
323 explicit IPCManager(
324 FrayManager &application)
325 : _application(application), _ownedThreads(std::make_unique<threads::ThreadManager>()),
327 {
328 fray::log::engineInfo("Constructed IPCManager.");
329 }
330
338 FrayManager &application)
339 : _application(application), _threads(&threads)
340 {
341 fray::log::engineInfo("Constructed IPCManager.");
342 }
343
348
354 {
355 if (_finished)
356 return;
357 _finished = true;
358 if (_started)
359 {
360 if (!_waited)
361 {
362 stop();
363 wait();
364 }
365 }
366 else
367 {
368 const auto servers = _servers;
369 for (const auto &s : servers)
370 if (s)
371 s->stop();
372 }
373 _servers.clear();
374 fray::log::engineInfo("Shutting down IPCManager.");
375 _application.finishShutdown();
376 _messages.shutdown();
377 }
378
386 F_ushort port)
387 {
388 if (_finished)
389 throw std::logic_error("Cannot create a server after IPC shutdown.");
390 auto s = std::make_shared<TCPServer>(_io, port, this);
391 s->start();
392 _servers.push_back(s);
393 return s;
394 }
395
402 F_ushort port)
403 {
404 auto it = std::find_if(_servers.begin(), _servers.end(),
405 [port](const TCPServerSP &sp)
406 { return sp && sp->port() == port; });
407 if (it != _servers.end())
408 _servers.erase(it);
409 // Stop io_context when no servers remain.
410 if (_servers.empty())
411 {
412 fray::log::engineInfo("No servers remaining; stopping io_context.");
413 _monitorTimer.cancel();
414 _shutdownTimer.cancel();
415 _startupTimer.cancel();
416 _loadingIntroTimer.cancel();
417 _io.stop();
418 }
419 }
420
426 {
427 if (_finished)
428 {
429 fray::log::engineError("Cannot start IPC after shutdown.");
430 return;
431 }
432 if (_started)
433 return;
434 _started = true;
435 _messageThread = _threads->spawn("engine-messages", [this](threads::StopToken)
436 { _messages.run(); });
437 _messages.post([this] { _monitor.start({PROCESS_KIND_ELECTRON_MAIN, 0}); });
439 _networkThread = _threads->spawn("network", [this](threads::StopToken)
440 {
441 try { _io.run(); }
442 catch (...) { networkFinished(); throw; }
444 });
445 }
446
453 const std::string &name,
454 const std::string &version)
455 {
456 BuildInfo info;
457 info.set_name(name);
458 info.set_version(version);
459 message::FrameOptions options{PROCESS_KIND_ELECTRON_RENDERER, COMMAND_LOADING_BUILD_INFO,
461 options.payload = info.SerializeAsString();
462 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
463 options.messageType = MESSAGE_TYPE_BUILD_INFO;
464 sendBuilt(options);
465 }
466
473 F_ulong operation,
474 std::uint32_t windowId)
475 {
476 WindowTarget target;
477 target.set_window_id(windowId);
478 message::FrameOptions options{PROCESS_KIND_ELECTRON_MAIN, operation};
479 options.payload = target.SerializeAsString();
480 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
481 options.messageType = MESSAGE_TYPE_WINDOW_TARGET;
482 sendBuilt(options);
483 }
484
491 const std::string &name,
492 const std::string &version)
493 {
494 _startupMainPending.store(true);
495 sendWindowCommand(COMMAND_WINDOW_LAUNCH, message::LOADING_WINDOW_ID);
496 sendLoadingBuildInfo(name, version);
497 if (!_messages.post([this]
498 {
499 _startupActive = true;
500 _startupFailed = false;
501 _loadingIntroElapsed = false;
502 _startupMilestones = engineStarted;
503 _startupPercent = 0;
504 if (_outgoing.isReady({PROCESS_KIND_ELECTRON_MAIN, 0}))
505 {
506 _startupMainPending.store(false);
508 }
511 }))
512 fray::log::engineError("Cannot check startup Main readiness: message thread is stopped.");
514 }
515
521 std::function<std::vector<std::string>()> reader)
522 {
523 _fontReader = std::move(reader);
524 }
525
530 {
531 _fontsThread = _threads->spawn("system-fonts", [this](threads::StopToken)
532 {
533 auto families = std::make_shared<std::vector<std::string>>(_fontReader());
534 if (!_messages.post([this, families]
535 {
536 _systemFonts = std::move(*families);
537 _systemFontsLoaded = true;
538 fray::log::engineInfo("Read %zu installed font families.", _systemFonts.size());
539 if (_outgoing.isReady({PROCESS_KIND_ELECTRON_RENDERER, message::MAIN_WINDOW_ID}))
542 }))
543 fray::log::engineError("Cannot publish system fonts: message thread is stopped.");
544 });
545 }
546
549 {
550 SystemFonts fontList;
551 for (const auto &family : _systemFonts)
552 fontList.add_families(family);
553 message::FrameOptions options{PROCESS_KIND_ELECTRON_RENDERER, COMMAND_SYSTEM_FONTS, message::MAIN_WINDOW_ID};
554 options.payload = fontList.SerializeAsString();
555 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
556 options.messageType = MESSAGE_TYPE_SYSTEM_FONTS;
557 options.flags = MESSAGE_FLAG_NO_CONSOLE;
558 sendBuilt(options);
559 }
560
576
579 {
580 boost::asio::post(_io, [this]
581 {
583 _loadingIntroTimer.async_wait([this](const boost::system::error_code &error)
584 {
585 if (error == boost::asio::error::operation_aborted) return;
586 if (!_messages.post([this, error]
587 {
588 if (!_startupActive || _startupFailed ||
589 _application.shutdownPhase() != FrayManager::ShutdownPhase::running) return;
590 if (error)
591 {
592 startupFailed("Loading intro timer failed: " + error.message());
593 return;
594 }
597 }))
598 fray::log::engineError("Cannot finish loading intro: message thread is stopped.");
599 });
600 });
601 }
602
608 const std::string &status = "")
609 {
610 unsigned completed = 0;
611 for (unsigned bit = engineStarted; bit <= systemFontsReady; bit <<= 1)
612 if (_startupMilestones & bit) ++completed;
613 StartupProgress progress;
614 const bool ready = !_startupFailed &&
615 _outgoing.isReady({PROCESS_KIND_ELECTRON_MAIN, 0}) &&
616 _outgoing.isReady({PROCESS_KIND_ELECTRON_RENDERER, message::MAIN_WINDOW_ID});
617 // The last step is held back until both windows are ready, so a full bar means the transition is happening.
618 _startupPercent = std::max(_startupPercent, completed == startupMilestoneCount && !ready ? 80u :
619 completed * 100 / startupMilestoneCount);
620 progress.set_percent(_startupPercent);
621 progress.set_status(status);
622 message::FrameOptions options{PROCESS_KIND_ELECTRON_RENDERER, COMMAND_STARTUP_PROGRESS,
624 options.payload = progress.SerializeAsString();
625 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
626 options.messageType = MESSAGE_TYPE_STARTUP_PROGRESS;
628 sendBuilt(options);
629 }
630
636 unsigned milestone)
637 {
640 return;
641 const bool changed = !(_startupMilestones & milestone);
642 _startupMilestones |= milestone;
643 const bool complete = _startupMilestones == allStartupMilestones &&
644 _outgoing.isReady({PROCESS_KIND_ELECTRON_MAIN, 0}) &&
645 _outgoing.isReady({PROCESS_KIND_ELECTRON_RENDERER, message::MAIN_WINDOW_ID});
646 if (complete || (changed && _startupMilestones != allStartupMilestones))
649 }
650
653 {
657 !_outgoing.isReady({PROCESS_KIND_ELECTRON_MAIN, 0}) ||
658 !_outgoing.isReady({PROCESS_KIND_ELECTRON_RENDERER, message::MAIN_WINDOW_ID}))
659 return;
660 _startupActive = false;
661 boost::asio::post(_io, [this] { _startupTimer.cancel(); });
662 _loadingWindowActive.store(false);
663 sendWindowCommand(COMMAND_WINDOW_CLOSE, message::LOADING_WINDOW_ID);
664 sendWindowCommand(COMMAND_WINDOW_SHOW, message::MAIN_WINDOW_ID);
665 }
666
671 const std::string &error)
672 {
673 if (!_startupActive || _startupFailed) return;
674 _startupFailed = true;
675 boost::asio::post(_io, [this] { _startupTimer.cancel(); _loadingIntroTimer.cancel(); });
676 fray::log::engineError("Application startup failed: %s", error.c_str());
677 sendStartupProgress("Startup failed: " + error);
678 }
679
685
688 {
689 const auto generation = ++_startupWarningGeneration;
690 boost::asio::post(_io, [this, generation]
691 {
692 _startupTimer.expires_after(std::chrono::seconds(15));
693 _startupTimer.async_wait([this, generation](const boost::system::error_code &error)
694 {
695 if (error == boost::asio::error::operation_aborted) return;
696 if (error)
697 {
698 fray::log::engineError("Startup warning timer failed: %s", error.message().c_str());
699 return;
700 }
701 if (!_messages.post([this, generation]
702 {
703 if (generation != _startupWarningGeneration || !_startupActive || _startupFailed ||
704 _application.shutdownPhase() != FrayManager::ShutdownPhase::running) return;
705 fray::log::engineWarn("Application startup is taking longer than expected.");
706 sendStartupProgress("Startup is taking longer than expected.");
707 }))
708 fray::log::engineError("Cannot report slow startup: message thread is stopped.");
709 });
710 });
711 }
712
714 bool loadingWindowActive() const { return _loadingWindowActive.load(); }
715
721 {
722 {
723 std::lock_guard<std::mutex> lock(_networkMutex);
724 _networkStopped = true;
725 }
726 _networkWake.notify_all();
727 }
728
734 {
735 _monitorTimer.expires_after(std::chrono::seconds(1));
736 _monitorTimer.async_wait([this](const boost::system::error_code &error)
737 {
738 if (error == boost::asio::error::operation_aborted) return;
739 if (error)
740 {
741 fray::log::engineError("Monitor timer failed: %s", error.message().c_str());
742 return;
743 }
744 _messages.post([this] { _outgoing.sweep(); _monitor.tick(); advanceShutdown(); });
746 });
747 }
748
754 {
756 return;
757 _shutdownPolling = true;
759 }
760
763 {
766 {
767 _shutdownPolling = false;
768 return;
769 }
770 boost::asio::post(_io, [this]
771 {
772 _shutdownTimer.expires_after(std::chrono::milliseconds(20));
773 _shutdownTimer.async_wait([this](const boost::system::error_code& error)
774 {
775 if (!error)
776 _messages.post([this] { armShutdownPoll(); });
777 });
778 });
779 }
780
783 {
785 return;
787 {
789 _application.beginConsoleShutdown();
790 }
791 if (!_application.consoleStopped())
792 return;
794 if (!_messages.post([this]
795 {
796 Frame frame;
797 // Silent, because the Engine is gone by the time Main could confirm it.
798 message::FrameOptions quit{PROCESS_KIND_ELECTRON_MAIN, COMMAND_QUIT};
799 quit.flags = message::SILENT_FLAGS;
800 const F_err result = message::FrameBuilder{}.build(quit, frame);
801 if (result != errors::NONE)
802 {
803 _shutdownCommandSent = false;
804 fray::log::engineError("Cannot build Engine close command: %s", errors::description(result));
805 return;
806 }
807 message::InData parsed;
808 if (message::parseFrame(frame, parsed) != errors::NONE)
809 {
810 _shutdownCommandSent = false;
811 fray::log::engineError("Cannot parse Engine close command.");
812 return;
813 }
814 const Frame identified = identify(frame, parsed.prefix);
815 boost::asio::post(_io, [this, identified]
816 {
817 const auto servers = _servers;
818 for (const auto& server : servers)
819 if (server)
820 server->broadcast(identified);
821 for (const auto& server : servers)
822 if (server)
823 server->drainAndStop();
824 });
825 }))
826 {
827 _shutdownCommandSent = false;
828 fray::log::engineError("Cannot queue Engine close command: message thread is stopped.");
829 }
830 }
831
839 {
840 if (_waited)
841 return;
842 {
843 std::unique_lock<std::mutex> lock(_networkMutex);
844 while (!_networkStopped)
845 {
846 _messages.post([this] { ++_heartbeat; });
847 _networkWake.wait_for(lock, std::chrono::seconds(1), [this] { return _networkStopped; });
848 }
849 }
851 _threads->join(_fontsThread);
852 _application.stopConsoleDelivery();
853 _messages.shutdown();
855 _waited = true;
856 }
857
860 {
861 boost::asio::post(_io, [this]()
862 {
863 const auto servers = _servers;
864 for (const auto &s : servers)
865 if (s)
866 s->stop(); });
867 }
868
877 bool send(
878 Frame frame)
879 {
880 if (!frame)
881 {
882 fray::log::engineError("Cannot send an empty frame pointer.");
883 return false;
884 }
885 if (!_messages.post([this, frame = std::move(frame)]() { route(frame); }))
886 {
887 fray::log::engineError("Cannot send message: message thread is shutting down.");
888 return false;
889 }
890 return true;
891 }
892
899 const message::FrameOptions &options)
900 {
901 Frame frame;
902 const F_err err = message::FrameBuilder{}.build(options, frame);
903 if (err != errors::NONE)
904 {
905 fray::log::engineError("Cannot build message: %s", errors::description(err));
906 return;
907 }
908 send(std::move(frame));
909 }
910
917 ProcessKind destination,
918 F_ulong destinationId)
919 {
920 message::FrameOptions options{destination, MSG_READY, destinationId};
921 options.category = MESSAGE_CATEGORY_MESSAGE;
923 sendBuilt(options);
924 }
925
933 const Frame& frame,
934 message::Prefix& prefix)
935 {
936 try
937 {
938 return message::assignUid(frame, prefix);
939 }
940 catch (const std::runtime_error& error)
941 {
942 fray::log::engineError("Cannot assign message UID: %s", error.what());
943 return frame;
944 }
945 catch (const std::bad_alloc& error)
946 {
947 fray::log::engineError("Cannot assign message UID: %s", error.what());
948 return frame;
949 }
950 }
951
958 const message::InData& incoming,
959 bool record)
960 {
961 const auto& prefix = incoming.prefix;
962 if (prefix.destinationId != 0 || message::isControl(prefix) ||
964 {
965 fray::log::engineError("Cannot route multicast: invalid recipient list or control operation.");
966 return;
967 }
968 bool engine = false;
969 bool remote = false;
970 for (const auto& recipient : incoming.header.recipients())
971 {
972 if (recipient.kind() == PROCESS_KIND_ENGINE && recipient.id() == 0)
973 engine = true;
974 else if ((recipient.kind() == PROCESS_KIND_ELECTRON_MAIN && recipient.id() == 0) ||
975 recipient.kind() == PROCESS_KIND_ELECTRON_RENDERER)
976 remote = true;
977 else
978 {
979 fray::log::engineError("Cannot route multicast: unsupported recipient %d:%u.",
980 static_cast<int>(recipient.kind()), recipient.id());
981 return;
982 }
983 }
985 _lastProgress = std::chrono::steady_clock::now();
986 const bool tracked = message::isTracked(prefix, incoming.header.flags());
987 if (record && tracked)
988 _application.recordCommand(incoming, *this, false);
989 if (engine)
990 {
991 if (tracked)
992 {
993 Receipt receipt;
994 receipt.set_uid(identity::hex(prefix.uid));
995 receipt.set_flags(incoming.header.flags());
996 receipt.set_sender(static_cast<ProcessKind>(prefix.senderKind));
997 receipt.set_destination(PROCESS_KIND_MULTICAST);
998 receipt.set_operation(prefix.operationId);
999 message::FrameOptions options{PROCESS_KIND_ENGINE, MSG_RECEIPT};
1000 options.category = MESSAGE_CATEGORY_MESSAGE;
1001 options.payload = receipt.SerializeAsString();
1002 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
1003 options.messageType = MESSAGE_TYPE_RECEIPT;
1004 if (incoming.header.has_target_project())
1005 options.targetProject = incoming.header.target_project();
1006 Frame frame;
1007 message::InData confirmation;
1008 if (message::FrameBuilder{}.build(options, frame) != errors::NONE ||
1009 message::parseFrame(frame, confirmation) != errors::NONE)
1010 fray::log::engineError("Cannot build Engine multicast receipt.");
1011 else
1012 {
1013 confirmation.frame = identify(frame, confirmation.prefix);
1014 _application.handleReceipt(confirmation, *this);
1015 }
1016 }
1017 auto local = incoming;
1018 local.prefix.destinationKind = PROCESS_KIND_ENGINE;
1019 local.prefix.destinationId = 0;
1020 if (prefix.category == MESSAGE_CATEGORY_COMMAND)
1021 _application.handleApplicationMessage(local, *this);
1022 else if (message::isNotice(prefix, MSG_RECEIPT))
1023 _application.handleReceipt(local, *this);
1024 else
1025 fray::log::engineWarn("Cannot handle multicast protocol message: unknown id=%u.", prefix.operationId);
1026 }
1027 if (remote && !_outgoing.send({PROCESS_KIND_ELECTRON_MAIN, 0}, incoming.frame, incoming.header.ttl_ms()) &&
1028 !message::isCommand(prefix, COMMAND_LOG_ENTRY))
1029 {
1030 fray::log::ConsoleSuppression suppressConsole;
1031 fray::log::engineInfo("Electron Main is not ready; the multicast message is waiting.");
1032 }
1033 }
1034
1044 const Frame &frame)
1045 {
1046 message::InData outgoing;
1047 const F_err err = message::parseFrame(frame, outgoing);
1048 if (err != fray::errors::NONE)
1049 {
1050 fray::log::engineError("Cannot send message: %s", fray::errors::description(err));
1051 return;
1052 }
1053 const Frame identified = identify(frame, outgoing.prefix);
1054 outgoing.frame = identified;
1055 const auto &prefix = outgoing.prefix;
1056 if (prefix.destinationKind == PROCESS_KIND_MULTICAST)
1057 {
1058 routeMulticast(outgoing, prefix.senderKind == PROCESS_KIND_ENGINE);
1059 return;
1060 }
1061 // The Engine's own commands for Main or the Renderer get the same log record and Console entry as anyone's.
1062 // Relayed frames were recorded when they arrived, so only the Engine's own are recorded here.
1063 if (prefix.senderKind == PROCESS_KIND_ENGINE &&
1064 (prefix.destinationKind == PROCESS_KIND_ELECTRON_MAIN || prefix.destinationKind == PROCESS_KIND_ELECTRON_RENDERER) &&
1065 message::isTracked(prefix, outgoing.header.flags()))
1066 _application.recordCommand(outgoing, *this, false);
1067 if (!message::isControl(prefix))
1068 {
1070 _lastProgress = std::chrono::steady_clock::now();
1071 }
1072 if (prefix.destinationKind == PROCESS_KIND_BROADCAST || message::isControl(prefix))
1073 transmit(identified);
1074 else if (!_outgoing.send({prefix.destinationKind, prefix.destinationId}, identified, outgoing.header.ttl_ms()) &&
1075 !message::isCommand(prefix, COMMAND_LOG_ENTRY)) // a log line about a log line would never end
1076 {
1077 fray::log::ConsoleSuppression suppressConsole;
1078 fray::log::engineInfo("%s is not ready; the message is waiting.",
1079 message::processInstanceName(prefix.destinationKind, prefix.destinationId).c_str());
1080 }
1081 }
1082
1088 Frame frame)
1089 {
1090 boost::asio::post(_io, [this, frame = std::move(frame)]()
1091 {
1092 for (const auto &s : _servers)
1093 if (s)
1094 s->broadcast(frame); });
1095 }
1096
1106 const message::InData &incoming)
1107 {
1108 const auto &prefix = incoming.prefix;
1109 if (prefix.senderKind == PROCESS_KIND_ENGINE || prefix.senderKind == PROCESS_KIND_BROADCAST)
1110 return;
1111 const Neighbor sender{prefix.senderKind, prefix.senderId};
1112 if (message::isNotice(prefix, MSG_READY))
1113 {
1114 const bool wasReady = _outgoing.isReady(sender);
1115 _monitor.observe(sender, true);
1116 // Answer a newly ready neighbor with our own READY so it need not ask. Only a change triggers it, so
1117 // the exchange ends after one reply each way.
1118 if (_outgoing.state(sender) != routing::NeighborState::degraded)
1119 _outgoing.markReady(sender);
1120 if (sender.first == PROCESS_KIND_ELECTRON_MAIN && sender.second == 0 && _outgoing.isReady(sender))
1121 {
1122 _startupMainPending.store(false);
1124 }
1125 if (sender.first == PROCESS_KIND_ELECTRON_RENDERER &&
1126 sender.second == message::MAIN_WINDOW_ID && _outgoing.isReady(sender))
1128 if (!wasReady && _outgoing.isReady(sender) && _systemFontsLoaded &&
1129 sender.first == PROCESS_KIND_ELECTRON_RENDERER && sender.second == message::MAIN_WINDOW_ID)
1131 if (!wasReady && _outgoing.isReady(sender))
1132 {
1133 fray::log::engineInfo("%s is connected to the Engine.",
1134 message::processInstanceName(prefix.senderKind, prefix.senderId).c_str());
1135 sendReady(prefix.senderKind, prefix.senderId);
1136 }
1137 }
1138 else if (message::isCommand(prefix, COMMAND_REQUEST_READY))
1139 {
1140 sendReady(prefix.senderKind, prefix.senderId);
1141 }
1142 else if (message::isCommand(prefix, COMMAND_PING))
1143 {
1144 HealthReport report;
1145 report.set_processed_count(_processedCount);
1146 report.set_heartbeat(_heartbeat);
1147 report.set_progress_age_ms(std::chrono::duration_cast<std::chrono::milliseconds>(
1148 std::chrono::steady_clock::now() - _lastProgress).count());
1149 for (const auto &queue : _outgoing.queueHealth())
1150 {
1151 auto *item = report.add_queues();
1152 item->set_destination(queue.destination.first);
1153 item->set_destination_id(queue.destination.second);
1154 item->set_depth(queue.depth);
1155 item->set_oldest_age_ms(queue.oldestAgeMs);
1156 }
1157 message::FrameOptions options{prefix.senderKind, COMMAND_PONG, prefix.senderId};
1158 options.payload = report.SerializeAsString();
1159 options.payloadType = PAYLOAD_TYPE_PROTOBUF;
1160 options.messageType = MESSAGE_TYPE_HEALTH_REPORT;
1161 options.flags = message::SILENT_FLAGS;
1162 sendBuilt(options);
1163 }
1164 else if (message::isCommand(prefix, COMMAND_PONG))
1165 {
1166 HealthReport report;
1167 if (incoming.header.payload_type() != PAYLOAD_TYPE_PROTOBUF ||
1168 incoming.header.message_type() != MESSAGE_TYPE_HEALTH_REPORT ||
1169 !report.ParseFromArray(incoming.payload(), static_cast<int>(incoming.payloadSize())))
1170 {
1171 fray::log::engineError("Invalid health report from %s.", message::processName(prefix.senderKind));
1172 }
1173 else
1174 {
1176 report.processed_count(), report.progress_age_ms(), report.heartbeat(), {}};
1177 for (const auto &queue : report.queues())
1178 health.queues.push_back({{queue.destination(), queue.destination_id()}, queue.depth(), queue.oldest_age_ms()});
1179 _monitor.report(sender, std::move(health));
1180 }
1181 }
1182 if (!message::isNotice(prefix, MSG_READY))
1183 _monitor.observe(sender, false);
1184 }
1185
1195 Frame frame)
1196 {
1197 if (!_messages.post([this, frame = std::move(frame)]()
1198 {
1199 message::Prefix prefix;
1200 F_err err = message::decodePrefix(frame->data(), frame->size(), prefix);
1201 if (err != fray::errors::NONE)
1202 {
1203 fray::log::engineError("Message processing failed: %s", fray::errors::description(err));
1204 return;
1205 }
1206 const bool multicast = prefix.destinationKind == PROCESS_KIND_MULTICAST;
1207 const routing::Destination destination = multicast ? routing::Destination::relay : routing::routeMessage(prefix);
1208 if (!multicast && (destination == routing::Destination::unsupported ||
1209 (destination == routing::Destination::relay && message::isControl(prefix)))
1210 )
1211 return;
1212 message::InData incoming;
1213 err = message::parseFrame(frame, incoming);
1214 if (err != fray::errors::NONE)
1215 fray::log::engineError("Message processing failed: %s", fray::errors::description(err));
1216 else
1217 {
1218 incoming.frame = identify(incoming.frame, incoming.prefix);
1219 if (multicast)
1220 {
1221 routeMulticast(incoming, true);
1222 return;
1223 }
1224 if (!message::isControl(prefix))
1225 {
1227 _lastProgress = std::chrono::steady_clock::now();
1228 }
1229 const bool tracked = message::isTracked(incoming.prefix, incoming.header.flags());
1230 if (destination == routing::Destination::relay)
1231 {
1232 // The router only splits the stream: log it, tell the Console, then pass the stamped original on.
1233 if (tracked)
1234 _application.recordCommand(incoming, *this, false);
1235 send(incoming.frame);
1236 return;
1237 }
1238 handleReadiness(incoming);
1239 // The Engine is the destination, so nothing else can confirm it; its entry is added as already received.
1240 if (tracked)
1241 _application.recordCommand(incoming, *this, true);
1242 if (prefix.category == MESSAGE_CATEGORY_COMMAND && !message::isControl(prefix))
1243 _application.handleApplicationMessage(incoming, *this);
1244 else if (message::isNotice(prefix, MSG_RECEIPT))
1245 _application.handleReceipt(incoming, *this);
1246 else if (prefix.category == MESSAGE_CATEGORY_MESSAGE && !message::isNotice(prefix, MSG_READY))
1247 fray::log::engineWarn("Cannot handle protocol message: unknown id=%u.", prefix.operationId);
1248 } }))
1249 fray::log::engineError("Cannot queue message: message thread is shutting down.");
1250 }
1251 };
1252
1253 /* ---- TCPServer method definitions ---- */
1254
1257 {
1258 if (!_accepting || _stopped)
1259 return;
1260 auto self = shared_from_this();
1261
1262 _acceptor.async_accept(
1263 [this, self](
1264 boost::system::error_code ec,
1265 boost::asio::ip::tcp::socket sock)
1266 {
1267 if (_stopped || !_accepting) return;
1268 if (!ec)
1269 {
1270 fray::log::engineInfo("Client connected.");
1271 auto session = std::make_shared<boost::asio::ip::tcp::socket>(std::move(sock));
1272 _sessions.insert(session);
1274 _connectionHandler(session);
1275 startRead(session);
1276 }
1277 if (_accepting && !_stopped)
1278 accept(); });
1279 }
1280
1282 std::shared_ptr<boost::asio::ip::tcp::socket> session)
1283 {
1284 auto self = shared_from_this();
1285 auto prefixBytes = std::make_shared<std::array<F_uchar, message::PREFIX_SIZE>>();
1286 boost::asio::async_read(
1287 *session,
1288 boost::asio::buffer(*prefixBytes),
1289 [this, self, session, prefixBytes](
1290 boost::system::error_code ec,
1291 std::size_t bytesRead)
1292 {
1293 if (ec)
1294 {
1295 if ((ec != boost::asio::error::eof || bytesRead != 0) && ec != boost::asio::error::operation_aborted)
1296 fray::log::engineError("Failed to read message prefix: %s", ec.message().c_str());
1297 closeSession(session);
1298 return;
1299 }
1300
1301 message::Prefix prefix;
1302 const F_err err = message::decodePrefix(prefixBytes->data(), prefixBytes->size(), prefix);
1303 if (err != errors::NONE)
1304 {
1305 fray::log::engineError("Invalid message prefix: %s", errors::description(err));
1306 closeSession(session);
1307 return;
1308 }
1309 if (prefix.headerLength > static_cast<F_ulong>(std::numeric_limits<int>::max()))
1310 {
1311 fray::log::engineError("Message header exceeds the protobuf size limit.");
1312 closeSession(session);
1313 return;
1314 }
1315 auto frame = std::make_shared<std::vector<F_uchar>>(message::PREFIX_SIZE + static_cast<size_t>(prefix.length));
1316 std::copy(prefixBytes->begin(), prefixBytes->end(), frame->begin());
1317
1318 boost::asio::async_read(
1319 *session, boost::asio::buffer(frame->data() + message::PREFIX_SIZE, prefix.length),
1320 [this, self, session, frame](
1321 boost::system::error_code ec2,
1322 std::size_t)
1323 {
1324 if (ec2)
1325 {
1326 if (ec2 != boost::asio::error::operation_aborted)
1327 fray::log::engineError("Failed to read message body: %s", ec2.message().c_str());
1328 closeSession(session);
1329 return;
1330 }
1331
1332 if (_manager)
1333 _manager->queueMessage(std::move(frame));
1334 if (!_stopped)
1335 startRead(session);
1336 });
1337 });
1338 }
1339
1341 Frame frame)
1342 {
1343 if (_stopped || _draining)
1344 return;
1345 const auto sessions = _sessions;
1346 for (const auto &session : sessions)
1347 write(session, frame);
1348 }
1349
1351 std::shared_ptr<boost::asio::ip::tcp::socket> session,
1352 Frame frame)
1353 {
1354 auto &queue = _outgoing[session];
1355 queue.push_back(std::move(frame));
1356 // Only one write may be in flight per socket.
1357 if (queue.size() == 1)
1358 writeNext(session);
1359 }
1360
1362 std::shared_ptr<boost::asio::ip::tcp::socket> session)
1363 {
1364 const auto found = _outgoing.find(session);
1365 if (found == _outgoing.end() || found->second.empty())
1366 return;
1367 auto frame = found->second.front();
1368 auto self = shared_from_this();
1369 boost::asio::async_write(
1370 *session,
1371 boost::asio::buffer(*frame),
1372 [this, self, session, frame](boost::system::error_code ec, std::size_t)
1373 {
1374 if (ec)
1375 {
1376 if (ec != boost::asio::error::operation_aborted)
1377 fray::log::engineError("Failed to write message: %s", ec.message().c_str());
1378 closeSession(session);
1379 return;
1380 }
1381 const auto pending = _outgoing.find(session);
1382 if (pending == _outgoing.end())
1383 return;
1384 pending->second.pop_front();
1385 if (!_stopped)
1386 writeNext(session);
1387 stopIfDrained();
1388 });
1389 }
1390
1392 Socket session)
1393 {
1394 boost::system::error_code ec;
1395 session->close(ec);
1396 _sessions.erase(session);
1397 _outgoing.erase(session);
1398 stopIfDrained();
1399 }
1400
1402 {
1403 if (!_draining || _stopped)
1404 return;
1405 for (const auto& queue : _outgoing)
1406 if (!queue.second.empty())
1407 return;
1408 stop();
1409 }
1410
1412 {
1413 if (_stopped || _draining)
1414 return;
1415 _draining = true;
1416 if (_sessions.empty())
1417 fray::log::engineWarn("No clients are connected to receive the Engine close command on port %d.", _port);
1418 _accepting = false;
1419 boost::system::error_code ec;
1420 _acceptor.cancel(ec);
1421 _acceptor.close(ec);
1422 _drainTimer.expires_after(std::chrono::seconds(1));
1423 auto self = shared_from_this();
1424 _drainTimer.async_wait([this, self](const boost::system::error_code& error)
1425 {
1426 if (error == boost::asio::error::operation_aborted)
1427 return;
1428 if (error)
1429 fray::log::engineError("Cannot monitor socket drain: %s", error.message().c_str());
1430 else
1431 fray::log::engineWarn("Socket writes did not drain before the shutdown deadline.");
1432 stop();
1433 });
1434 stopIfDrained();
1435 }
1436
1438 {
1439 if (_stopped)
1440 return;
1441 _stopped = true;
1442 _accepting = false;
1443
1444 boost::system::error_code ec;
1445 _drainTimer.cancel();
1446 _acceptor.cancel(ec);
1447 if (_acceptor.is_open())
1448 _acceptor.close(ec);
1449
1450 for (auto &s : _sessions)
1451 {
1452 if (!s)
1453 continue;
1454 boost::system::error_code sec;
1455 s->shutdown(boost::asio::ip::tcp::socket::shutdown_both, sec);
1456 s->close(sec);
1457 }
1458 _sessions.clear();
1459 _outgoing.clear();
1460
1461 fray::log::engineInfo("Stopped TCPServer on port %d.", _port);
1462
1463 if (_manager)
1464 _manager->removeTCPServer(_port);
1465 }
1466
1467 } // namespace ipc
1468} // namespace fray
1469
1470// The handler needs the complete IPCManager type to send its response.
1471#include "fray_message_handler.hpp"
1472
1473#endif
Owns and coordinates projects, their queues, application work, prompts, and logs. Project work runs o...
Owns the TCP servers and the threads around them.
F_void advanceShutdown()
Advances Engine-local shutdown and sends Main an independent terminal command when ready.
F_void armShutdownPoll()
Advances shutdown now and re-arms the poll on the network thread while it is still pending.
F_void queueMessage(Frame frame)
Called by the network thread: queues a received message for the engine message thread....
F_void sendSystemFonts()
Message thread only. Sends the installed font families to the application Renderer,...
F_void removeTCPServer(F_ushort port)
Forgets the server on the port (called by TCPServer::stop on the network thread). When no servers rem...
std::function< std::vector< std::string >()> _fontReader
boost::asio::steady_timer _startupTimer
F_void finishStartupIfReady()
Transitions only after startup milestones and the loading intro timer have both finished.
F_void setFontReader(std::function< std::vector< std::string >()> reader)
Sets how installed font families are listed during startup. Call before startLoading().
Frame identify(const Frame &frame, message::Prefix &prefix)
Assigns a routing UID without preventing delivery if UID generation fails.
static constexpr unsigned allStartupMilestones
std::atomic< bool > _startupMainPending
Keeps the initial startup queue until Main first announces readiness.
threads::ThreadManager::Id _networkThread
IPCManager(threads::ThreadManager &threads, FrayManager &application)
Creates an IPCManager whose threads register with a ThreadManager owned by someone else.
~IPCManager()
Finishes IPC and application shutdown if not already finished.
F_void route(const Frame &frame)
Router thread only. Delivers an outgoing frame, or queues it if its destination is not ready....
F_void sendLoadingBuildInfo(const std::string &name, const std::string &version)
Queues build information for the loading Renderer without waiting for it to start.
F_void networkFinished()
Marks the network thread as finished and wakes wait(). Takes _networkMutex briefly....
static constexpr unsigned startupMilestoneCount
F_void transmit(Frame frame)
Writes a frame to every connected client. Safe from any thread (posts to the network thread).
F_void start()
Starts the network thread and the engine message thread, then returns. Does nothing if already starte...
F_void sendReady(ProcessKind destination, F_ulong destinationId)
Sends a readiness notification without waiting for the destination.
threads::ThreadManager * _threads
FrayManager & _application
F_void routeMulticast(const message::InData &incoming, bool record)
Records one multicast command, handles the Engine recipient, and queues one frame to Main.
F_void stop()
Asks every server to stop (run on the network thread). Safe from any thread; wait() returns once the ...
F_void mainFrameIsReady()
Records Main's announcement that the application window has a first frame.
threads::TaskQueue _messages
F_void startupFailed(const std::string &error)
Records Main's independent report that application-window startup failed.
F_void pollShutdown()
Starts a short-interval local poll that advances shutdown until its terminal command is queued....
routing::NeighborMonitor< Neighbor > _monitor
unsigned _startupWarningGeneration
std::unique_ptr< threads::ThreadManager > _ownedThreads
boost::asio::steady_timer _monitorTimer
F_void scheduleLoadingIntro()
Starts the Engine-owned, nonblocking loading logo intro timer.
F_void startLoading(const std::string &name, const std::string &version)
Queues the initial hidden loading window and its application information.
threads::ThreadManager::Id _fontsThread
F_void scheduleStartupWarning()
Warns about slow startup without completing it or blocking any process.
F_void sendWindowCommand(F_ulong operation, std::uint32_t windowId)
Queues a window operation for Electron Main.
routing::OutgoingRouter< Neighbor, Frame > _outgoing
bool send(Frame frame)
Hands a message to the router and returns at once. Safe from any thread. The router delivers it now i...
boost::asio::steady_timer _shutdownTimer
IPCManager(FrayManager &application)
Creates an IPCManager with its own ThreadManager, which is convenient for tests.
F_void readSystemFonts()
Reads the installed font families on a worker thread, then hands them to the message thread,...
bool loadingWindowActive() const
Whether startup logs should include the loading window.
F_void recordStartupMilestone(unsigned milestone)
Records an independent startup event and advances the Engine-owned transition.
std::condition_variable _networkWake
F_void sendBuilt(const message::FrameOptions &options)
Builds an Engine frame from the options and sends it with send(). Safe from any thread....
std::atomic< bool > _loadingWindowActive
std::chrono::steady_clock::time_point _lastProgress
static constexpr auto loadingIntroDuration
std::vector< std::string > _systemFonts
std::vector< TCPServerSP > _servers
std::pair< ProcessKind, F_ulong > Neighbor
TCPServerSP createTCPServer(F_ushort port)
Creates a TCP server and starts it accepting. Must be called before start(). Not thread-safe; call fr...
threads::ThreadManager::Id _messageThread
boost::asio::io_context _io
boost::asio::steady_timer _loadingIntroTimer
F_void scheduleMonitor()
Arms the one-second monitor timer; each firing queues a router sweep and neighbor-monitor tick on the...
F_void handleReadiness(const message::InData &incoming)
Message thread only. Handles readiness and health traffic from a neighbor. A READY marks the sender r...
F_void finish()
Stops IPC, releases servers, and shuts the application down exactly once. Call on the controlling thr...
F_void wait()
Blocks until every server has stopped and the queued messages have been handled. While waiting it pos...
F_void sendStartupProgress(const std::string &status="")
Publishes the Engine's startup snapshot to the loading Renderer.
F_void loadingReadyToShow()
Records loading readiness and independently commands both startup windows.
TCPServer(boost::asio::io_context &ctx, F_ushort port, IPCManager *manager)
Binds a listening IPv4 socket on the port. Throws (boost) if the port cannot be bound.
F_void startRead(std::shared_ptr< boost::asio::ip::tcp::socket > session)
Reads one frame (prefix, then header + payload) from the client and hands it to IPCManager::queueMess...
F_void accept()
Starts (and re-arms) an asynchronous accept; each client gets a session and starts being read....
F_void drainAndStop()
Stops accepting and drains queued socket writes for at most one second. Network thread only.
boost::asio::ip::tcp::acceptor _acceptor
F_void sendTo(Socket session, Frame frame)
Queues a message for one client. Network thread only. Logs an error and sends nothing if session or f...
~TCPServer()
Logs that the server was destroyed.
F_void setConnectionHandler(ConnectionHandler handler)
Sets the callback run on the network thread for each accepted client. Set before start().
F_void stop()
Stops accepting, closes every client, drops pending writes and asks the owning IPCManager to remove t...
F_ushort port() const
The port the server is listening on (the OS-chosen one if 0 was requested).
ConnectionHandler _connectionHandler
F_void write(Socket session, Frame frame)
Appends a frame to the session's write queue and starts writing if none is in flight.
boost::asio::steady_timer _drainTimer
F_void closeSession(Socket session)
Closes the client socket and forgets its session and pending writes (queued frames are lost).
std::map< std::shared_ptr< boost::asio::ip::tcp::socket >, std::deque< Frame > > _outgoing
IPCManager * _manager
std::set< std::shared_ptr< boost::asio::ip::tcp::socket > > _sessions
F_void broadcast(Frame frame)
Queues a message for every connected client. Network thread only; use IPCManager::send elsewhere.
F_void start()
Begins accepting clients (called by IPCManager::createTCPServer). Network thread / before the io_cont...
F_void writeNext(std::shared_ptr< boost::asio::ip::tcp::socket > session)
Writes the frame at the front of the session's queue; on completion pops it and writes the next....
F_void stopIfDrained()
Stops the server once all locally queued writes have completed.
Keeps lines in the persistent log but out of the Console for this thread's scope.
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
Tracks neighbor liveness and health from what the router hears, and reports state transitions....
The router thread's single source of truth about which neighbors are ready, plus the messages waiting...
Cooperative cancellation shared by every copy of a token. Copies share one state guarded by an intern...
A task loop that runs on one thread. Other threads post work to it. Tasks run one at a time in postin...
Registry of the engine's threads: starts them, names them, asks them to stop and joins them....
std::uint64_t Id
Handle for a spawned thread; ids start at 1 and are never reused.
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
const F_char * description(code err)
Formats an error code as "Error <number>: <description>". Not thread-safe: the text lives in a shared...
Definition errors.hpp:96
std::string hex(const Uid &uid)
Formats a routing UID as lowercase hexadecimal.
Definition uid.hpp:38
std::shared_ptr< TCPServer > TCPServerSP
Shared pointer to a TCPServer.
std::shared_ptr< const std::vector< F_uchar > > Frame
Shared, immutable, fully built frame (prefix + header + payload); shared between threads without copy...
std::shared_ptr< boost::asio::ip::tcp::socket > Socket
Shared TCP client socket; only the network thread may use it.
std::function< void(Socket)> ConnectionHandler
Callback invoked on the network thread with each newly accepted client socket.
F_void engineInfo(const F_char *fmt,...)
Log info for Engine.
F_void engineError(const F_char *fmt,...)
Log error for Engine.
F_void engineWarn(const F_char *fmt,...)
Log warning for Engine.
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
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
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
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
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
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
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
Destination routeMessage(const message::Prefix &prefix)
Decides where an incoming message goes from its prefix destination. Pure apart from logging; may run ...
NeighborState
Readiness of a neighbor process as seen by the router. unknown: nothing known yet; probing: readiness...
MonitorCommand
What the monitor asks its Send callback to transmit: probe = ask for readiness, ping = request a heal...
Destination
Where an incoming message should be handled.
Everything FrameBuilder needs to build one outgoing Engine message.
Definition message.hpp:398
std::optional< std::string > targetProject
Definition message.hpp:412
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
uint16_t F_ushort
Unsigned 16-bit integer (used for ports).
Definition types.hpp:30
uint32_t F_ulong
Unsigned 32-bit integer.
Definition types.hpp:34
void F_void
Alias for void.
Definition types.hpp:20
bool F_bool
Alias for bool.
Definition types.hpp:22