MayaFlux 1.0.0
Digital-First Multimedia Processing Framework
Loading...
Searching...
No Matches
Session.cpp
Go to the documentation of this file.
1#include "Session.hpp"
2
4#include "Lila/Lila.hpp"
5
9
10#ifdef MAYAFLUX_PLATFORM_WINDOWS
12#endif
13
14namespace MayaFlux::Host {
15
16namespace {
17
18 constexpr size_t k_stage_count = 4;
19
20 struct State {
21 std::shared_ptr<Lila::Lila> instance;
22 std::optional<Lila::Address> address;
23 bool starting {};
24 std::array<std::vector<std::string>, k_stage_count> staged;
25 std::set<std::string> libraries;
26 };
27
28 enum class Outcome : uint8_t {
29 Staged,
30 Duplicate,
31 Running,
32 Starting
33 };
34
35 Memory::SnapshotCell<State> g_state;
36
37 struct ObserverEntry {
38 ObserverId id;
39 std::shared_ptr<const EvalObserver> observer;
40 };
41
42 Memory::SnapshotCell<std::vector<ObserverEntry>> g_observers;
43 std::atomic<ObserverId> g_next_observer { 1 };
44
45 void dispatch_eval(void*, const Lila::EvalReport& report)
46 {
47 const auto observers = g_observers.read();
48 if (!observers) {
49 return;
50 }
51 for (const auto& entry : *observers) {
52 (*entry.observer)(report);
53 }
54 }
55
56 std::unexpected<Failure> refuse(std::string message, std::vector<std::filesystem::path> tried = {})
57 {
58 return std::unexpected(Failure { .message = std::move(message), .tried = std::move(tried) });
59 }
60
61 size_t index_of(detail::Stage stage)
62 {
63 return static_cast<size_t>(stage);
64 }
65
66 std::string where_text(const std::optional<Lila::Address>& address)
67 {
68 if (!address) {
69 return "nowhere";
70 }
71 if (const auto* tcp = std::get_if<Lila::TcpAddress>(&*address)) {
72 return tcp->host + ":" + std::to_string(tcp->port);
73 }
74 return "socket " + std::get<Lila::UnixAddress>(*address).path.value_or(std::filesystem::path {}).string();
75 }
76
77 std::shared_ptr<Lila::Lila> running_instance()
78 {
79 auto view = g_state.read();
80 return view ? view->instance : nullptr;
81 }
82
83 bool library_known(const std::string& path)
84 {
85 auto view = g_state.read();
86 return view && view->libraries.contains(path);
87 }
88
89 Result<void> run_eval(Lila::Lila& lila, const std::string& code)
90 {
91 if (auto evaluated = lila.eval(code); !evaluated) {
92 return refuse(std::string(evaluated.error()));
93 }
94 return {};
95 }
96
97 Result<void> run_load(Lila::Lila& lila, const std::string& path)
98 {
99 if (auto loaded = lila.load_library(path); !loaded) {
100 return refuse(std::string(loaded.error()), { path });
101 }
102 return {};
103 }
104
105 Result<void> apply_now(Lila::Lila& lila, detail::Stage stage, const std::string& value)
106 {
107 if (stage == detail::Stage::Eval) {
108 return run_eval(lila, value);
109 }
110
111 if (stage == detail::Stage::Library) {
112 if (library_known(value)) {
113 return {};
114 }
115 auto loaded = run_load(lila, value);
116 if (loaded) {
117 g_state.update([&value](State& state) { state.libraries.insert(value); });
118 }
119 return loaded;
120 }
121
122 return refuse("takes effect only before start_session: " + value);
123 }
124
125}
126
127namespace detail {
128
129 Result<void> apply_or_stage(Stage stage, std::string value)
130 {
131 for (;;) {
132 Outcome outcome = Outcome::Staged;
133
134 g_state.update([&](State& state) {
135 if (state.instance) {
136 outcome = Outcome::Running;
137 return false;
138 }
139 if (state.starting) {
140 outcome = Outcome::Starting;
141 return false;
142 }
143 if (stage == Stage::Library && !state.libraries.insert(value).second) {
144 outcome = Outcome::Duplicate;
145 return false;
146 }
147 state.staged[index_of(stage)].push_back(value);
148 outcome = Outcome::Staged;
149 return true;
150 });
151
152 if (outcome == Outcome::Staged || outcome == Outcome::Duplicate) {
153 return {};
154 }
155 if (outcome == Outcome::Starting) {
156 return refuse("session is starting");
157 }
158
159 if (auto instance = running_instance()) {
160 return apply_now(*instance, stage, value);
161 }
162 }
163 }
164
166 {
168
169 std::string message;
170 switch (failure.reason) {
171 case Reason::EmptyRequest:
172 message = "empty request";
173 break;
174 case Reason::InvalidName:
175 message = "invalid name";
176 break;
177 case Reason::Missing:
178 message = "not found";
179 break;
180 case Reason::NotDirectory:
181 message = "not a directory";
182 break;
183 case Reason::NotRegularFile:
184 message = "not a regular file";
185 break;
186 case Reason::MarkerMissing:
187 message = "marker file missing";
188 break;
189 case Reason::TooLong:
190 message = "path too long";
191 break;
192 case Reason::Unsafe:
193 message = "unsafe location";
194 break;
195 case Reason::NotSocket:
196 message = "not a socket";
197 break;
198 case Reason::InUse:
199 message = "already in use";
200 break;
201 case Reason::StaleNotRemoved:
202 message = "stale entry could not be removed";
203 break;
204 }
205 if (!failure.request.empty()) {
206 message += ": " + failure.request;
207 }
208 return Failure { .message = std::move(message), .tried = failure.tried };
209 }
210
211}
212
213Result<void> start_session(const Lila::Address& where)
214{
215 enum class Refusal : uint8_t {
216 None,
217 Running,
218 Starting
219 };
220
221 Refusal refusal = Refusal::None;
222 std::optional<Lila::Address> running;
223 std::array<std::vector<std::string>, k_stage_count> staged;
224
225 g_state.update([&](State& state) {
226 if (state.instance) {
227 refusal = Refusal::Running;
228 running = state.address;
229 return false;
230 }
231 if (state.starting) {
232 refusal = Refusal::Starting;
233 return false;
234 }
235 refusal = Refusal::None;
236 staged = std::exchange(state.staged, {});
237 state.starting = true;
238 return true;
239 });
240
241 if (refusal == Refusal::Running) {
242 return refuse("session already running on " + where_text(running));
243 }
244 if (refusal == Refusal::Starting) {
245 return refuse("session is starting");
246 }
247
248 auto instance = std::make_shared<Lila::Lila>();
249 instance->add_eval_observer(&dispatch_eval, nullptr);
250
251 for (const auto& path : staged[index_of(detail::Stage::IncludePath)]) {
252 instance->add_include_path(path);
253 }
254 for (const auto& flag : staged[index_of(detail::Stage::CompileFlag)]) {
255 instance->add_compile_flag(flag);
256 }
257
258 const auto abandon = [&instance](Failure failure) -> Result<void> {
259 instance->stop_listening();
260 g_state.update([](State& state) {
261 state.starting = false;
262 state.libraries.clear();
263 });
264 return std::unexpected(std::move(failure));
265 };
266
267 if (const auto ready = instance->initialize(true); !ready) {
268 return abandon(Failure { .message = "initialization failed: " + std::string(ready.error()), .tried = {} });
269 }
270
271 for (const auto& library : staged[index_of(detail::Stage::Library)]) {
272 if (auto loaded = run_load(*instance, library); !loaded) {
273 return abandon(std::move(loaded.error()));
274 }
275 }
276 for (const auto& code : staged[index_of(detail::Stage::Eval)]) {
277 if (auto evaluated = run_eval(*instance, code); !evaluated) {
278 return abandon(std::move(evaluated.error()));
279 }
280 }
281
282 if (const auto listening = instance->listen(where); !listening) {
283 return abandon(Failure { .message = "listen failed: " + std::string(listening.error()), .tried = {} });
284 }
285
286 const auto* resolved = instance->address();
287 const std::optional<Lila::Address> bound = resolved ? std::optional<Lila::Address>(*resolved) : std::nullopt;
288 g_state.update([&](State& state) {
289 state.instance = instance;
290 state.address = bound;
291 state.starting = false;
292 });
293
294 LILA_INFO(Lila::Emitter::SYSTEM, "start_session: running on " + where_text(bound));
295 return {};
296}
297
298void stop_session(bool clear_persistent_store)
299{
300 std::shared_ptr<Lila::Lila> instance;
301 std::optional<Lila::Address> stopped;
302
303 g_state.update([&](State& state) {
304 if (!state.instance) {
305 instance.reset();
306 return false;
307 }
308 instance = std::move(state.instance);
309 stopped = std::exchange(state.address, std::nullopt);
310 state.libraries.clear();
311 return true;
312 });
313
314 if (!instance) {
315 return;
316 }
317
318 LILA_INFO(Lila::Emitter::SYSTEM,
319 "stop_session: stopping on " + where_text(stopped));
320
321 instance->stop_listening();
322 instance.reset();
323
324 if (clear_persistent_store) {
326 LILA_DEBUG(Lila::Emitter::SYSTEM, "stop_session: cleared persistent store");
327 }
328}
329
331{
332 auto view = g_state.read();
333 return view && view->instance;
334}
335
336std::optional<Lila::Address> session_address()
337{
338 auto view = g_state.read();
339 return view && view->instance ? view->address : std::nullopt;
340}
341
342Result<void> eval(const std::string& code)
343{
345}
346
348{
349 const ObserverId id = g_next_observer.fetch_add(1);
350 const auto held = std::make_shared<const EvalObserver>(std::move(observer));
351 g_observers.update([&](std::vector<ObserverEntry>& entries) {
352 entries.push_back({ .id = id, .observer = held });
353 });
354 return id;
355}
356
358{
359 g_observers.update([id](std::vector<ObserverEntry>& entries) {
360 return std::erase_if(entries, [id](const ObserverEntry& entry) { return entry.id == id; }) > 0;
361 });
362}
363
364Result<void> eval_file(const std::filesystem::path& path)
365{
366 auto located = Platform::acquire_library(Platform::LibraryFromPath { .path = path });
367 if (!located) {
368 return std::unexpected(detail::to_failure(located.error()));
369 }
370
371 const std::string file = located->path.generic_string();
372 if (file.find_first_of("\"\r\n") != std::string::npos) {
373 return refuse("path cannot be included: " + file);
374 }
375
376 return eval("#include \"" + file + "\"");
377}
378
379Result<void*> symbol_address(const std::string& name)
380{
381 auto instance = running_instance();
382 if (!instance) {
383 return refuse("no active session");
384 }
385
386 void* address = instance->get_symbol_address(name);
387 if (!address) {
388 return refuse("symbol not found: " + name);
389 }
390 return address;
391}
392
393} // namespace MayaFlux::Host
#define LILA_DEBUG(emitter, msg)
#define LILA_INFO(emitter, msg)
Status load_library(const std::string &path)
Load a shared library into the JIT symbol table.
Definition Lila.cpp:186
Status eval(const std::string &code)
Evaluates a C++ code snippet.
Definition Lila.cpp:136
Failure to_failure(const Platform::AcquireFailure &failure)
Definition Session.cpp:165
Result< void > apply_or_stage(Stage stage, std::string value)
Apply an item to the running session, or stage it until start_session.
Definition Session.cpp:129
std::expected< T, Failure > Result
Result of a Host call.
Definition Session.hpp:26
std::function< void(const EvalReport &)> EvalObserver
Definition Session.hpp:87
Result< void * > symbol_address(const std::string &name)
Address of a symbol defined in the running session.
Definition Session.cpp:379
Result< void > eval(const std::string &code)
Evaluate a code snippet.
Definition Session.cpp:342
std::optional< Lila::Address > session_address()
Where the running session listens, with anything resolved at start filled in.
Definition Session.cpp:336
uint64_t ObserverId
Identifies an observer for remove_eval_observer.
Definition Session.hpp:92
void remove_eval_observer(ObserverId id)
Stop observing.
Definition Session.cpp:357
bool session_active()
True if a session is running in this process.
Definition Session.cpp:330
Result< void > start_session(const Lila::Address &where)
Start a Lila interpreter and a server inside this process.
Definition Session.cpp:213
ObserverId on_eval(EvalObserver observer)
Observe every evaluation in the session, whoever sent it.
Definition Session.cpp:347
Result< void > eval_file(const std::filesystem::path &path)
Evaluate a source file by including it.
Definition Session.cpp:364
void stop_session(bool clear_persistent_store)
Stop the running session.
Definition Session.cpp:298
Acquired< LibraryLocation > acquire_library(const LibrarySource &source)
Resolve a library request to a location the loader can open.
void refuse(std::string_view message)
Definition Layers.hpp:74
void cleanup_persistent_store()
Definition Persist.hpp:14
Why a Host call was refused, with every path that was checked.
Definition Session.hpp:17
std::vector< std::filesystem::path > tried
Why an acquisition request was refused, with every path that was checked.
A shared library at an explicit file path, absolute or relative to the working directory.