LeviLamina
Loading...
Searching...
No Matches
ServiceManager.h
1#pragma once
2
3#include <type_traits>
4
5#include "ll/api/event/EventBus.h"
6#include "ll/api/event/MultiListener.h"
7#include "ll/api/event/service/ServiceEvents.h"
8#include "ll/api/mod/NativeMod.h"
9#include "ll/api/service/Service.h"
10#include "ll/api/service/ServiceId.h"
11
12#include "ll/api/Expected.h"
13
14namespace ll::service {
15
17 enum class ErrorType : char {
18 NotExist = 0,
19 VersionMismatch = 1,
20 };
21 using enum ErrorType;
22
23 ErrorType code;
24 size_t version;
25
26 GetServiceError(ErrorType code, size_t version = 0) : code(code), version(version) {}
27
28 LLAPI std::string message() const noexcept override;
29};
30
32 std::string name;
33 size_t version;
34 std::string modName;
35 std::shared_ptr<Service> service;
36};
37
39public:
40 LLNDAPI static ServiceManager& getInstance();
41
42 template <IsService T>
43 event::ListenerPtr subscribeService(std::function<void(std::shared_ptr<T> const&)> const& fn) {
44 if (auto service = getService<T>(); service) {
45 fn(*service);
46 }
47 auto listener =
49 [fn](auto&& event) {
50 if (event.service()->getServiceId() == T::ServiceId) {
51 if constexpr (std::is_same_v<
52 std::remove_cvref_t<decltype((event))>,
53 event::server::ServiceUnregisterEvent>) {
54 fn(nullptr);
55 } else {
56 fn(std::static_pointer_cast<T>(event.service()));
57 }
58 }
59 }
60 );
61 event::EventBus::getInstance().addListener(listener);
62 return listener;
63 }
64
65 template <IsService T>
66 Expected<std::shared_ptr<T>> getService() {
67 auto res = getService(getServiceId<T>);
68 if (!res) {
69 return forwardError(res.error());
70 }
71 return std::static_pointer_cast<T>(*res);
72 }
73
74 LLNDAPI Expected<std::shared_ptr<Service>> getService(ServiceIdView const& id);
75
76 LLNDAPI std::optional<QueryServiceResult> queryService(std::string_view name);
77
78 LLAPI bool registerService(
79 std::shared_ptr<Service> const& service,
80 std::shared_ptr<mod::Mod> const& mod = mod::NativeMod::current()
81 );
82
83 LLAPI bool unregisterService(ServiceIdView const& id);
84
85 LLAPI void unregisterService(mod::Mod const& mod);
86
87 ServiceManager(ServiceManager const&) = delete;
89 ServiceManager& operator=(ServiceManager const&) = delete;
90 ServiceManager& operator=(ServiceManager&&) = delete;
91
92private:
93 class Impl;
94 std::unique_ptr<Impl> impl;
95
98};
99
100} // namespace ll::service
Definition Expected.h:22
Definition MultiListener.h:12
Definition Mod.h:17
Definition ServiceId.h:24
Definition ServiceManager.h:38
Definition code.h:5
Definition ServiceManager.h:16
Definition ServiceManager.h:31