Anklang 0.3.0-460-gc4ef46ba
ASE — Anklang Sound Engine (C++)

« « « Anklang Documentation
Loading...
Searching...
No Matches
jsonapi.cc
Go to the documentation of this file.
1 // This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
2#include "jsonapi.hh"
3#include "server.hh"
4#include "main.hh"
5#include "internal.hh"
6
7#define GCDEBUG(...) Ase::debug ("gc", __VA_ARGS__)
8#define GCDEBUG_ENABLED() Ase::debug_key_enabled ("gc")
9
10namespace Ase {
11
12static String subprotocol_authentication;
13
14void
15jsonapi_set_subprotocol (const String &subprotocol)
16{
17 subprotocol_authentication = subprotocol;
18}
19
20// == JsonapiConnection ==
21class JsonapiConnection;
22using JsonapiConnectionP = std::shared_ptr<JsonapiConnection>;
23using JsonapiConnectionW = std::weak_ptr<JsonapiConnection>;
24static JsonapiConnectionP current_message_conection;
25
26static bool
27is_localhost (const String &url, int port)
28{
29 return Re::search ("^https?://(localhost|127\\.0\\.0\\.1)(:[0-9]+)?/", url, Re::I) >= 0;
30}
31
33 Jsonipc::InstanceMap imap_, gcmap_;
34 void
35 log (const String &message) override
36 {
37 printerr ("%s: %s\n", nickname(), message);
38 }
39 int
40 validate() override
41 {
42 using namespace AnsiColors;
43 const auto C1 = color (BOLD), C0 = color (BOLD_OFF);
44 const Info info = get_info();
45 const String origin = info.header ("Origin") + "/";
46 const bool localhost_origin = is_localhost (origin, info.lport);
47 const bool subproto_ok = (info.subs.size() == 0 && subprotocol_authentication.empty()) ||
48 (info.subs.size() == 1 && subprotocol_authentication == info.subs[0]);
49 if (localhost_origin && subproto_ok)
50 return 0; // OK
51 // log rejection
52 String why;
53 if (!localhost_origin) why = "Bad Origin";
54 else if (!subproto_ok) why = "Bad Subprotocol";
55 const String ua = info.header ("User-Agent");
56 if (logflags_ & 2)
57 log (string_format ("%sREJECT:%s %s:%d/ (%s) - %s", C1, C0, info.remote, info.rport, why, ua));
58 return -1; // reject
59 }
60 void
61 opened() override
62 {
63 using namespace AnsiColors;
64 const auto C1 = color (BOLD), C0 = color (BOLD_OFF);
65 const Info info = get_info();
66 const String ua = info.header ("User-Agent");
67 if (logflags_ & 4)
68 log (string_format ("%sACCEPT:%s %s:%d/ - %s", C1, C0, info.remote, info.rport, ua));
69 }
70 void
71 closed() override
72 {
73 using namespace AnsiColors;
74 const auto C1 = color (BOLD), C0 = color (BOLD_OFF);
75 if (logflags_ & 4)
76 log (string_format ("%sCLOSED%s", C1, C0));
77 trigger_destroy_hooks();
78 }
79 void
80 message (const String &message) override
81 {
83 assert_return (conp);
84 String reply;
85 // wait for main loop callback completion via semaphore
87 main_jobs += [&message, &reply, conp, &sem, this] () {
88 current_message_conection = conp;
89 reply = handle_jsonipc (message);
90 current_message_conection = nullptr;
91 sem.post();
92 };
93 nickname(); // cache socket nickname for use during errors
94 sem.wait(); // synchronize with sem.post()
95 // when queueing asynchronously, we have to use WebSocketConnectionP
96 if (!reply.empty())
97 send_text (reply);
98 }
99 String handle_jsonipc (const std::string &message);
100 std::vector<JsTrigger> triggers_; // HINT: use unordered_map if this becomes slow
101public:
102 explicit JsonapiConnection (WebSocketConnection::Internals &internals, int logflags) :
103 WebSocketConnection (internals, logflags)
104 {}
106 {
107 trigger_destroy_hooks();
108 }
109 bool
110 renew_gc ()
111 {
112 const bool starting_gc = imap_.mark_unused();
113 GCDEBUG ("%s: imap_=%d%s\n", __func__, imap_.size(), starting_gc ? " (duplicate)" : "");
114 return starting_gc; // false: duplicate request, waiting for report_gc
115 }
116 bool
117 report_gc (const std::vector<size_t> &ids)
118 {
119 const size_t preerved = imap_.purge_unused (ids);
120 GCDEBUG ("%s: considered=%d retained=%d purged=%d active=%d\n", __func__,
121 ids.size(), preerved, ids.size() - preerved, imap_.size());
122 return imap_.size();
123 }
125 trigger_lookup (const String &id)
126 {
127 for (auto it = triggers_.begin(); it != triggers_.end(); it++)
128 if (id == it->id())
129 return *it;
130 return {};
131 }
132 void
133 trigger_remove (const String &id)
134 {
135 trigger_lookup (id).destroy();
136 }
137 void
138 trigger_create (const String &id)
139 {
140 using namespace Jsonipc;
142 assert_return (jsonapi_connection_p);
143 std::weak_ptr<JsonapiConnection> selfw = jsonapi_connection_p;
144 const int logflags = logflags_;
145 // marshal remote trigger
146 auto trigger_remote = [selfw, id, logflags] (ValueS &&args) // weak_ref avoids cycles
147 {
148 JsonapiConnectionP selfp = selfw.lock();
149 return_unless (selfp);
150 const String msg = jsonobject_to_string ("method", id /*"Jsonapi/Trigger/_%%%"*/, "params", args);
151 if (logflags & 8)
152 selfp->log (string_format ("⬰ %s", msg));
153 selfp->send_text (msg);
154 };
155 JsTrigger trigger = JsTrigger::create (id, trigger_remote);
156 triggers_.push_back (trigger);
157 // marshall remote destroy notification and erase triggers_ entry
158 auto erase_trigger = [selfw, id, logflags] () // weak_ref avoids cycles
159 {
160 std::shared_ptr<JsonapiConnection> selfp = selfw.lock();
161 return_unless (selfp);
162 if (selfp->is_open())
163 {
164 ValueS args { id };
165 const String msg = jsonobject_to_string ("method", "Jsonapi/Trigger/killed", "params", args);
166 if (logflags & 8)
167 selfp->log (string_format ("↚ %s", msg));
168 selfp->send_text (msg);
169 }
170 Aux::erase_first (selfp->triggers_, [id] (auto &t) { return id == t.id(); });
171 };
172 trigger.ondestroy (erase_trigger);
173 }
174 void
175 trigger_destroy_hooks()
176 {
178 old.swap (triggers_); // speed up erase_trigger() searches
179 for (auto &trigger : old)
180 trigger.destroy();
181 custom_data_destroy();
182 }
183};
184
186jsonapi_make_connection (WebSocketConnection::Internals &internals, int logflags)
187{
188 return std::make_shared<JsonapiConnection> (internals, logflags);
189}
190
191#define ERROR500(WHAT) \
192 Jsonipc::bad_invocation (-32500, \
193 __FILE__ ":" \
194 ASE_CPP_STRINGIFY (__LINE__) ": " \
195 "Internal Server Error: " \
196 WHAT)
197#define assert_500(c) (__builtin_expect (static_cast<bool> (c), 1) ? (void) 0 : throw ERROR500 (#c) )
198
200make_dispatcher()
201{
202 using namespace Jsonipc;
203 static IpcDispatcher *dispatcher = [] () {
204 dispatcher = new IpcDispatcher();
205 dispatcher->add_method ("Jsonapi/renew-gc",
206 [] (CallbackInfo &cbi)
207 {
208 assert_500 (current_message_conection);
209 if (cbi.n_args() > 0)
210 throw Jsonipc::bad_invocation (-32602, "Invalid params");
211 const auto ret = current_message_conection->renew_gc ();
212 cbi.set_result (to_json (ret, cbi.allocator()).Move());
213 });
214 dispatcher->add_method ("Jsonapi/report-gc",
215 [] (CallbackInfo &cbi)
216 {
217 assert_500 (current_message_conection);
218 if (cbi.n_args() != 1)
219 throw Jsonipc::bad_invocation (-32602, "Invalid params");
220 const auto ids = from_json<std::vector<size_t>> (cbi.ntharg (0));
221 const auto ret = current_message_conection->report_gc (ids);
222 cbi.set_result (to_json (ret, cbi.allocator()).Move());
223 });
224 dispatcher->add_method ("Jsonapi/initialize",
225 [] (CallbackInfo &cbi)
226 {
227 assert_500 (current_message_conection);
228 Server &server = ASE_SERVER;
229 std::shared_ptr<Server> serverp = shared_ptr_cast<Server> (&server);
230 cbi.set_result (to_json (serverp, cbi.allocator()).Move());
231 });
232 dispatcher->add_method ("Jsonapi/Trigger/create",
233 [] (CallbackInfo &cbi)
234 {
235 assert_500 (current_message_conection);
236 const String triggerid = cbi.n_args() == 1 ? from_json<String> (cbi.ntharg (0)) : "";
237 if (triggerid.compare (0, 17, "Jsonapi/Trigger/_") != 0)
238 throw Jsonipc::bad_invocation (-32602, "Invalid params");
239 current_message_conection->trigger_create (triggerid);
240 });
241 dispatcher->add_method ("Jsonapi/Trigger/remove",
242 [] (CallbackInfo &cbi)
243 {
244 assert_500 (current_message_conection);
245 const String triggerid = cbi.n_args() == 1 ? from_json<String> (cbi.ntharg (0)) : "";
246 if (triggerid.compare (0, 17, "Jsonapi/Trigger/_") != 0)
247 throw Jsonipc::bad_invocation (-32602, "Invalid params");
248 current_message_conection->trigger_remove (triggerid);
249 });
250 return dispatcher;
251 } ();
252 return dispatcher;
253}
254
255String
256JsonapiConnection::handle_jsonipc (const std::string &message)
257{
258 if (logflags_ & 8)
259 log (string_format ("→ %s", message.size() > 1024 ? message.substr (0, 1020) + "..." + message.back() : message));
260 Jsonipc::Scope message_scope (imap_);
261 String reply;
262 { // enfore notifies *before* reply (and the corresponding log() messages)
263 CoalesceNotifies coalesce_notifies; // coalesce multiple "notify:detail" emissions
264 reply = make_dispatcher()->dispatch_message (message);
265 } // coalesced notifications occour *here*
266 if (logflags_ & 8)
267 {
268 const char *errorat = strstr (reply.c_str(), "\"error\":{");
269 if (errorat && errorat > reply.c_str() && (errorat[-1] == ',' || errorat[-1] == '{'))
270 {
271 using namespace AnsiColors;
272 auto R1 = color (BOLD) + color (FG_RED), R0 = color (FG_DEFAULT) + color (BOLD_OFF);
273 log (string_format ("%s←%s %s", R1, R0, reply));
274 }
275 else
276 log (string_format ("← %s", reply.size() > 1024 ? reply.substr (0, 1020) + "..." + reply.back() : reply));
277 }
278 return reply;
279}
280
281// == JsTrigger ==
283 using Func = std::function<void (ValueS)>;
284 const String id;
285 Func func;
286 using VoidFunc = std::function<void()>;
287 std::vector<VoidFunc> destroyhooks;
288 friend class JsTrigger;
289 /*ctor*/ Impl () = delete;
290 /*copy*/ Impl (const Impl&) = delete;
291 Impl& operator= (const Impl&) = delete;
292public:
293 ~Impl ()
294 {
295 destroy();
296 }
297 Impl (const Func &f, const String &_id) :
298 id (_id), func (f)
299 {}
300 void
301 destroy ()
302 {
303 func = nullptr;
304 while (!destroyhooks.empty())
305 {
306 VoidFunc destroyhook = destroyhooks.back();
307 destroyhooks.pop_back();
308 destroyhook();
309 }
310 }
311};
312
313void
314JsTrigger::ondestroy (const VoidFunc &vf)
315{
316 assert_return (p_);
317 if (vf)
318 p_->destroyhooks.push_back (vf);
319}
320
321void
322JsTrigger::call (ValueS &&args) const
323{
324 assert_return (p_);
325 if (p_->func)
326 p_->func (std::move (args));
327}
328
329JsTrigger
330JsTrigger::create (const String &triggerid, const JsTrigger::Impl::Func &f)
331{
332 JsTrigger trigger;
333 trigger.p_ = std::make_shared<JsTrigger::Impl> (f, triggerid);
334 assert_return (f != nullptr, trigger);
335 return trigger;
336}
337
338String
339JsTrigger::id () const
340{
341 return p_ ? p_->id : "";
342}
343
344void
345JsTrigger::destroy ()
346{
347 if (p_)
348 p_->destroy();
349}
350
351JsTrigger::operator bool () const noexcept
352{
353 return p_ && p_->func;
354}
355
356JsTrigger
357ConvertJsTrigger::lookup (const String &triggerid)
358{
359 if (current_message_conection)
360 return current_message_conection->trigger_lookup (triggerid);
361 assert_return (current_message_conection, {});
362 return {};
363}
364
365CustomDataContainer*
366jsonapi_connection_data ()
367{
368 if (current_message_conection)
369 return current_message_conection.get();
370 return nullptr;
371}
372
373JsonapiBinarySender
374jsonapi_connection_sender ()
375{
376 return_unless (current_message_conection, {});
377 JsonapiConnectionW conw = current_message_conection;
378 return [conw] (const String &blob) {
379 JsonapiConnectionP conp = conw.lock();
380 return conp ? conp->send_binary (blob) : false;
381 };
382}
383
384} // Ase
385
386// Build generated bindings
388
389#include "testing.hh"
390
391namespace { // Anon
392
393TEST_INTEGRITY (jsonapi_tests);
394static void
395jsonapi_tests()
396{
397 using namespace Ase;
398 using IdStringMap = std::map<size_t,std::string>;
399 IdStringMap tmap;
400 for (size_t i = 1; i <= 99; i++)
401 tmap[1000 - i] = string_format ("%d", i);
402 TASSERT (tmap.size() == 99);
403 for (auto it = tmap.begin(), next = it; it != tmap.end() ? ++next, 1 : 0; it = next) // keep next ahead of it, but avoid ++end
404 tmap.erase (it);
405 TASSERT (tmap.size() == 0);
406}
407
408} // Anon
T back(T... args)
Callback mechanism for Jsonapi/Jsonipc.
Definition value.hh:123
static ssize_t search(const String &regex, const String &input, Flags=DEFAULT)
Find regex in input and return match position >= 0 or return < 0 otherwise.
Definition regex.cc:217
int wait() noexcept
Unlock ScopedSemaphore.
Definition platform.cc:902
int post() noexcept
Unlock ScopedSemaphore.
Definition platform.cc:893
bool send_text(const String &message)
Returns true if text message was sent.
Definition websocket.cc:264
Keep track of temporary instances during IpcDispatcher::dispatch_message().
Definition jsonipc.hh:163
T empty(T... args)
#define assert_return(expr,...)
Return from the current function if expr is unmet and issue an assertion warning.
Definition internal.hh:29
#define return_unless(cond,...)
Return silently if cond does not evaluate to true with return value ...
Definition internal.hh:71
#define TEST_INTEGRITY(FUNC)
Register func as an integrity test.
Definition internal.hh:77
std::string color(Colors acolor, Colors c1, Colors c2, Colors c3, Colors c4, Colors c5, Colors c6)
Return ANSI code for the specified color if stdout & stderr should be colorized, see colorize_tty().
Definition platform.cc:190
size_t erase_first(C &container, const std::function< bool(typename C::value_type const &value)> &pred)
Erase first element for which pred() is true in vector or list.
Definition utils.hh:337
The Anklang C++ API namespace.
Definition api.hh:9
std::string string_format(const char *format, const Args &...args) __attribute__((__format__(__printf__
Format a string similar to sprintf(3) with support for std::string and std::ostringstream convertible...
JobQueue main_jobs(call_main_loop)
Execute a job callback in the Ase main loop.
Definition main.hh:39
std::string String
Convenience alias for std::string.
Definition cxxaux.hh:35
T next(T... args)
T size(T... args)
strstr
Context for calling C++ functions from Json.
Definition jsonipc.hh:450
Jsonipc exception that is relayed to caller when thrown during invocations.
Definition jsonipc.hh:144
T substr(T... args)
#define TASSERT(cond)
Unconditional test assertion, enters breakpoint if not fullfilled.
Definition testing.hh:24