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