Anklang-0.3.0.dev797+g4e3241f3 anklang-0.3.0.dev797+g4e3241f3
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 if (!main_loop->has_quit()) {
86 current_message_conection = conp;
87 reply = this->handle_jsonipc (message);
88 current_message_conection = nullptr;
89 }
90 else
91 reply = "{id:0,error:{code:-32601,message:\"Method not found: endpoint shutting down\"}}\n";
92 if (!reply.empty())
93 send_text (reply);
94 }
95 String handle_jsonipc (const std::string &message);
96 std::vector<JsTrigger> triggers_; // HINT: use unordered_map if this becomes slow
97public:
98 explicit JsonapiConnection (WebSocketConnection::Internals &internals, int logflags) :
99 WebSocketConnection (internals, logflags)
100 {}
102 {
103 trigger_destroy_hooks();
104 }
105 bool
106 renew_gc ()
107 {
108 const bool starting_gc = imap_.mark_unused();
109 GCDEBUG ("%s: imap_=%d%s\n", __func__, imap_.size(), starting_gc ? " (duplicate)" : "");
110 return starting_gc; // false: duplicate request, waiting for report_gc
111 }
112 bool
113 report_gc (const std::vector<size_t> &ids)
114 {
115 const size_t preerved = imap_.purge_unused (ids);
116 GCDEBUG ("%s: considered=%d retained=%d purged=%d active=%d\n", __func__,
117 ids.size(), preerved, ids.size() - preerved, imap_.size());
118 return imap_.size();
119 }
121 trigger_lookup (const String &id)
122 {
123 for (auto it = triggers_.begin(); it != triggers_.end(); it++)
124 if (id == it->id())
125 return *it;
126 return {};
127 }
128 void
129 trigger_remove (const String &id)
130 {
131 trigger_lookup (id).destroy();
132 }
133 void
134 trigger_create (const String &id)
135 {
136 using namespace Jsonipc;
138 assert_return (jsonapi_connection_p);
139 std::weak_ptr<JsonapiConnection> selfw = jsonapi_connection_p;
140 const int logflags = logflags_;
141 // marshal remote trigger
142 auto trigger_remote = [selfw, id, logflags] (ValueS &&args) // weak_ref avoids cycles
143 {
144 JsonapiConnectionP selfp = selfw.lock();
145 return_unless (selfp);
146 const String msg = jsonobject_to_string ("method", id /*"Jsonapi/Trigger/_%%%"*/, "params", args);
147 if (logflags & 8)
148 selfp->log (string_format ("⬰ %s", msg));
149 selfp->send_text (msg);
150 };
151 JsTrigger trigger = JsTrigger::create (id, trigger_remote);
152 triggers_.push_back (trigger);
153 // marshall remote destroy notification and erase triggers_ entry
154 auto erase_trigger = [selfw, id, logflags] () // weak_ref avoids cycles
155 {
156 std::shared_ptr<JsonapiConnection> selfp = selfw.lock();
157 return_unless (selfp);
158 if (selfp->is_open())
159 {
160 ValueS args { id };
161 const String msg = jsonobject_to_string ("method", "Jsonapi/Trigger/killed", "params", args);
162 if (logflags & 8)
163 selfp->log (string_format ("↚ %s", msg));
164 selfp->send_text (msg);
165 }
166 Aux::erase_first (selfp->triggers_, [id] (auto &t) { return id == t.id(); });
167 };
168 trigger.ondestroy (erase_trigger);
169 }
170 void
171 trigger_destroy_hooks()
172 {
174 old.swap (triggers_); // speed up erase_trigger() searches
175 for (auto &trigger : old)
176 trigger.destroy();
177 custom_data_destroy();
178 }
179};
180
182jsonapi_make_connection (WebSocketConnection::Internals &internals, int logflags)
183{
184 return std::make_shared<JsonapiConnection> (internals, logflags);
185}
186
187#define ERROR500(WHAT) \
188 Jsonipc::bad_invocation (-32500, \
189 __FILE__ ":" \
190 ASE_CPP_STRINGIFY (__LINE__) ": " \
191 "Internal Server Error: " \
192 WHAT)
193#define assert_500(c) (__builtin_expect (static_cast<bool> (c), 1) ? (void) 0 : throw ERROR500 (#c) )
194
196make_dispatcher()
197{
198 using namespace Jsonipc;
199 static IpcDispatcher *dispatcher = [] () {
200 dispatcher = new IpcDispatcher();
201 dispatcher->add_method ("Jsonapi/renew-gc",
202 [] (CallbackInfo &cbi)
203 {
204 assert_500 (current_message_conection);
205 if (cbi.n_args() > 0)
206 throw Jsonipc::bad_invocation (-32602, "Invalid params");
207 const auto ret = current_message_conection->renew_gc ();
208 cbi.set_result (to_json (ret, cbi.allocator()).Move());
209 });
210 dispatcher->add_method ("Jsonapi/report-gc",
211 [] (CallbackInfo &cbi)
212 {
213 assert_500 (current_message_conection);
214 if (cbi.n_args() != 1)
215 throw Jsonipc::bad_invocation (-32602, "Invalid params");
216 const auto ids = from_json<std::vector<size_t>> (cbi.ntharg (0));
217 const auto ret = current_message_conection->report_gc (ids);
218 cbi.set_result (to_json (ret, cbi.allocator()).Move());
219 });
220 dispatcher->add_method ("Jsonapi/initialize",
221 [] (CallbackInfo &cbi)
222 {
223 assert_500 (current_message_conection);
224 Server &server = ASE_SERVER;
225 std::shared_ptr<Server> serverp = shared_ptr_cast<Server> (&server);
226 cbi.set_result (to_json (serverp, cbi.allocator()).Move());
227 });
228 dispatcher->add_method ("Jsonapi/Trigger/create",
229 [] (CallbackInfo &cbi)
230 {
231 assert_500 (current_message_conection);
232 const String triggerid = cbi.n_args() == 1 ? from_json<String> (cbi.ntharg (0)) : "";
233 if (triggerid.compare (0, 17, "Jsonapi/Trigger/_") != 0)
234 throw Jsonipc::bad_invocation (-32602, "Invalid params");
235 current_message_conection->trigger_create (triggerid);
236 });
237 dispatcher->add_method ("Jsonapi/Trigger/remove",
238 [] (CallbackInfo &cbi)
239 {
240 assert_500 (current_message_conection);
241 const String triggerid = cbi.n_args() == 1 ? from_json<String> (cbi.ntharg (0)) : "";
242 if (triggerid.compare (0, 17, "Jsonapi/Trigger/_") != 0)
243 throw Jsonipc::bad_invocation (-32602, "Invalid params");
244 current_message_conection->trigger_remove (triggerid);
245 });
246 return dispatcher;
247 } ();
248 return dispatcher;
249}
250
251String
252JsonapiConnection::handle_jsonipc (const std::string &message)
253{
254 if (logflags_ & 8)
255 log (string_format ("→ %s", message.size() > 1024 ? message.substr (0, 1020) + "..." + message.back() : message));
256 Jsonipc::Scope message_scope (imap_);
257 String reply;
258 { // enfore notifies *before* reply (and the corresponding log() messages)
259 CoalesceNotifies coalesce_notifies; // coalesce multiple "notify:detail" emissions
260 reply = make_dispatcher()->dispatch_message (message);
261 } // coalesced notifications occour *here*
262 if (logflags_ & 8)
263 {
264 const char *errorat = strstr (reply.c_str(), "\"error\":{");
265 if (errorat && errorat > reply.c_str() && (errorat[-1] == ',' || errorat[-1] == '{'))
266 {
267 using namespace AnsiColors;
268 auto R1 = color (BOLD) + color (FG_RED), R0 = color (FG_DEFAULT) + color (BOLD_OFF);
269 log (string_format ("%s←%s %s", R1, R0, reply));
270 }
271 else
272 log (string_format ("← %s", reply.size() > 1024 ? reply.substr (0, 1020) + "..." + reply.back() : reply));
273 }
274 return reply;
275}
276
277// == JsTrigger ==
279 using Func = std::function<void (ValueS)>;
280 const String id;
281 Func func;
282 using VoidFunc = std::function<void()>;
283 std::vector<VoidFunc> destroyhooks;
284 friend class JsTrigger;
285 /*ctor*/ Impl () = delete;
286 /*copy*/ Impl (const Impl&) = delete;
287 Impl& operator= (const Impl&) = delete;
288public:
289 ~Impl ()
290 {
291 destroy();
292 }
293 Impl (const Func &f, const String &_id) :
294 id (_id), func (f)
295 {}
296 void
297 destroy ()
298 {
299 func = nullptr;
300 while (!destroyhooks.empty())
301 {
302 VoidFunc destroyhook = destroyhooks.back();
303 destroyhooks.pop_back();
304 destroyhook();
305 }
306 }
307};
308
309void
310JsTrigger::ondestroy (const VoidFunc &vf)
311{
312 assert_return (p_);
313 if (vf)
314 p_->destroyhooks.push_back (vf);
315}
316
317void
318JsTrigger::call (ValueS &&args) const
319{
320 assert_return (p_);
321 if (p_->func)
322 p_->func (std::move (args));
323}
324
325JsTrigger
326JsTrigger::create (const String &triggerid, const JsTrigger::Impl::Func &f)
327{
328 JsTrigger trigger;
329 trigger.p_ = std::make_shared<JsTrigger::Impl> (f, triggerid);
330 assert_return (f != nullptr, trigger);
331 return trigger;
332}
333
334String
335JsTrigger::id () const
336{
337 return p_ ? p_->id : "";
338}
339
340void
341JsTrigger::destroy ()
342{
343 if (p_)
344 p_->destroy();
345}
346
347JsTrigger::operator bool () const noexcept
348{
349 return p_ && p_->func;
350}
351
352JsTrigger
353ConvertJsTrigger::lookup (const String &triggerid)
354{
355 if (current_message_conection)
356 return current_message_conection->trigger_lookup (triggerid);
357 assert_return (current_message_conection, {});
358 return {};
359}
360
361CustomDataContainer*
362jsonapi_connection_data ()
363{
364 if (current_message_conection)
365 return current_message_conection.get();
366 return nullptr;
367}
368
369JsonapiBinarySender
370jsonapi_connection_sender ()
371{
372 return_unless (current_message_conection, {});
373 JsonapiConnectionW conw = current_message_conection;
374 return [conw] (const String &blob) {
375 JsonapiConnectionP conp = conw.lock();
376 return conp ? conp->send_binary (blob) : false;
377 };
378}
379
380} // Ase
381
382// Build generated bindings
384
385#include "testing.hh"
386
387namespace { // Anon
388
389TEST_INTEGRITY (jsonapi_tests);
390static void
391jsonapi_tests()
392{
393 using namespace Ase;
394 using IdStringMap = std::map<size_t,std::string>;
395 IdStringMap tmap;
396 for (size_t i = 1; i <= 99; i++)
397 tmap[1000 - i] = string_format ("%d", i);
398 TASSERT (tmap.size() == 99);
399 for (auto it = tmap.begin(), next = it; it != tmap.end() ? ++next, 1 : 0; it = next) // keep next ahead of it, but avoid ++end
400 tmap.erase (it);
401 TASSERT (tmap.size() == 0);
402}
403
404} // Anon
T back(T... args)
DataListContainer - typesafe storage and retrieval of arbitrary members.
Definition utils.hh:86
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
bool send_text(const String &message)
Returns true if text message was sent.
Definition websocket.cc:408
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:73
#define TEST_INTEGRITY(FUNC)
Register func as an integrity test.
Definition internal.hh:79
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:191
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:268
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...
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