cutelyst  3.7.0
A C++ Web Framework built on top of Qt, using the simple approach of Catalyst (Perl) framework.
context.cpp
1 /*
2  * SPDX-FileCopyrightText: (C) 2013-2022 Daniel Nicoletti <dantti12@gmail.com>
3  * SPDX-License-Identifier: BSD-3-Clause
4  */
5 #include "context_p.h"
6 
7 #include "common.h"
8 #include "request.h"
9 #include "response.h"
10 #include "action.h"
11 #include "dispatcher.h"
12 #include "controller.h"
13 #include "application.h"
14 #include "stats.h"
15 #include "enginerequest.h"
16 
17 #include "config.h"
18 
19 #include <QUrl>
20 #include <QUrlQuery>
21 #include <QCoreApplication>
22 #include <QBuffer>
23 
24 using namespace Cutelyst;
25 
26 Context::Context(ContextPrivate *priv) : d_ptr(priv)
27 {
28 }
29 
31  d_ptr(new ContextPrivate(app, app->engine(), app->dispatcher(), app->plugins()))
32 {
33  auto req = new DummyRequest(this);
34  req->body = new QBuffer(this);
35  req->body->open(QBuffer::ReadWrite);
36  req->context = this;
37 
38  d_ptr->response = new Response(app->defaultHeaders(), req);
39  d_ptr->request = new Request(req);
40  d_ptr->request->d_ptr->engine = d_ptr->engine;
41 }
42 
43 Context::~Context()
44 {
45  delete d_ptr->request;
46  delete d_ptr->response;
47  delete d_ptr;
48 }
49 
50 bool Context::error() const noexcept
51 {
52  Q_D(const Context);
53  return !d->error.isEmpty();
54 }
55 
56 void Context::error(const QString &error)
57 {
58  Q_D(Context);
59  if (error.isEmpty()) {
60  d->error.clear();
61  } else {
62  d->error << error;
63  qCCritical(CUTELYST_CORE) << error;
64  }
65 }
66 
67 QStringList Context::errors() const noexcept
68 {
69  Q_D(const Context);
70  return d->error;
71 }
72 
73 bool Context::state() const noexcept
74 {
75  Q_D(const Context);
76  return d->state;
77 }
78 
79 void Context::setState(bool state) noexcept
80 {
81  Q_D(Context);
82  d->state = state;
83 }
84 
85 Engine *Context::engine() const noexcept
86 {
87  Q_D(const Context);
88  return d->engine;
89 }
90 
91 Application *Context::app() const noexcept
92 {
93  Q_D(const Context);
94  return d->app;
95 }
96 
97 Response *Context::response() const noexcept
98 {
99  Q_D(const Context);
100  return d->response;
101 }
102 
103 Response *Context::res() const noexcept
104 {
105  Q_D(const Context);
106  return d->response;
107 }
108 
109 Action *Context::action() const noexcept
110 {
111  Q_D(const Context);
112  return d->action;
113 }
114 
115 QString Context::actionName() const noexcept
116 {
117  Q_D(const Context);
118  return d->action->name();
119 }
120 
121 QString Context::ns() const noexcept
122 {
123  Q_D(const Context);
124  return d->action->ns();
125 }
126 
127 Request *Context::request() const noexcept
128 {
129  Q_D(const Context);
130  return d->request;
131 }
132 
133 Request *Context::req() const noexcept
134 {
135  Q_D(const Context);
136  return d->request;
137 }
138 
140 {
141  Q_D(const Context);
142  return d->dispatcher;
143 }
144 
145 QString Cutelyst::Context::controllerName() const
146 {
147  Q_D(const Context);
148  return QString::fromLatin1(d->action->controller()->metaObject()->className());
149 }
150 
151 Controller *Context::controller() const noexcept
152 {
153  Q_D(const Context);
154  return d->action->controller();
155 }
156 
157 Controller *Context::controller(const QString &name) const
158 {
159  Q_D(const Context);
160  return d->dispatcher->controllers().value(name);
161 }
162 
163 View *Context::customView() const noexcept
164 {
165  Q_D(const Context);
166  return d->view;
167 }
168 
169 View *Context::view(const QString &name) const
170 {
171  Q_D(const Context);
172  return d->app->view(name);
173 }
174 
175 View *Context::view(QStringView name) const
176 {
177  Q_D(const Context);
178  return d->app->view(name);
179 }
180 
181 bool Context::setCustomView(const QString &name)
182 {
183  Q_D(Context);
184  d->view = d->app->view(name);
185  return d->view;
186 }
187 
188 QVariantHash &Context::stash()
189 {
190  Q_D(Context);
191  return d->stash;
192 }
193 
194 QVariant Context::stash(const QString &key) const
195 {
196  Q_D(const Context);
197  return d->stash.value(key);
198 }
199 
200 QVariant Context::stash(const QString &key, const QVariant &defaultValue) const
201 {
202  Q_D(const Context);
203  return d->stash.value(key, defaultValue);
204 }
205 
206 QVariant Context::stashTake(const QString &key)
207 {
208  Q_D(Context);
209  return d->stash.take(key);
210 }
211 
212 bool Context::stashRemove(const QString &key)
213 {
214  Q_D(Context);
215  return d->stash.remove(key);
216 }
217 
218 void Context::setStash(const QString &key, const QVariant &value)
219 {
220  Q_D(Context);
221  d->stash.insert(key, value);
222 }
223 
224 void Context::setStash(const QString &key, const ParamsMultiMap &map)
225 {
226  Q_D(Context);
227  d->stash.insert(key, QVariant::fromValue(map));
228 }
229 
230 QStack<Component *> Context::stack() const noexcept
231 {
232  Q_D(const Context);
233  return d->stack;
234 }
235 
236 QUrl Context::uriFor(const QString &path, const QStringList &args, const ParamsMultiMap &queryValues) const
237 {
238  Q_D(const Context);
239 
240  QUrl uri = d->request->uri();
241 
242  QString _path;
243  if (path.isEmpty()) {
244  // ns must NOT return a leading slash
245  const QString controllerNS = d->action->controller()->ns();
246  if (!controllerNS.isEmpty()) {
247  _path.prepend(controllerNS);
248  }
249  } else {
250  _path = path;
251  }
252 
253  if (!args.isEmpty()) {
254  if (_path.compare(u"/") == 0) {
255  _path += args.join(u'/');
256  } else {
257  _path = _path + u'/' + args.join(u'/');
258  }
259  }
260 
261  if (!_path.startsWith(u'/')) {
262  _path.prepend(u'/');
263  }
264  uri.setPath(_path, QUrl::DecodedMode);
265 
266  QUrlQuery query;
267  if (!queryValues.isEmpty()) {
268  // Avoid a trailing '?'
269  if (queryValues.size()) {
270  auto it = queryValues.constEnd();
271  while (it != queryValues.constBegin()) {
272  --it;
273  query.addQueryItem(it.key(), it.value());
274  }
275  }
276  }
277  uri.setQuery(query);
278 
279  return uri;
280 }
281 
282 QUrl Context::uriFor(Action *action, const QStringList &captures, const QStringList &args, const ParamsMultiMap &queryValues) const
283 {
284  Q_D(const Context);
285 
286  QUrl uri;
287  Action *localAction = action;
288  if (!localAction) {
289  localAction = d->action;
290  }
291 
292  QStringList localArgs = args;
293  QStringList localCaptures = captures;
294 
295  Action *expandedAction = d->dispatcher->expandAction(this, action);
296  if (expandedAction->numberOfCaptures() > 0) {
297  while (localCaptures.size() < expandedAction->numberOfCaptures()
298  && localArgs.size()) {
299  localCaptures.append(localArgs.takeFirst());
300  }
301  } else {
302  QStringList localCapturesAux = localCaptures;
303  localCapturesAux.append(localArgs);
304  localArgs = localCapturesAux;
305  localCaptures = QStringList();
306  }
307 
308  const QString path = d->dispatcher->uriForAction(localAction, localCaptures);
309  if (path.isEmpty()) {
310  qCWarning(CUTELYST_CORE) << "Can not find action for" << localAction << localCaptures;
311  return uri;
312  }
313 
314  uri = uriFor(path, localArgs, queryValues);
315  return uri;
316 }
317 
318 QUrl Context::uriForAction(const QString &path, const QStringList &captures, const QStringList &args, const ParamsMultiMap &queryValues) const
319 {
320  Q_D(const Context);
321 
322  QUrl uri;
323  Action *action = d->dispatcher->getActionByPath(path);
324  if (!action) {
325  qCWarning(CUTELYST_CORE) << "Can not find action for" << path;
326  return uri;
327  }
328 
329  uri = uriFor(action, captures, args, queryValues);
330  return uri;
331 }
332 
333 bool Context::detached() const noexcept
334 {
335  Q_D(const Context);
336  return d->detached;
337 }
338 
339 void Context::detach(Action *action)
340 {
341  Q_D(Context);
342  if (action) {
343  d->dispatcher->forward(this, action);
344  } else {
345  d->detached = true;
346  }
347 }
348 
349 void Context::detachAsync() noexcept
350 {
351  Q_D(Context);
352  ++d->actionRefCount;
353 }
354 
356 {
357  Q_D(Context);
358  if (--d->actionRefCount) {
359  return;
360  }
361 
362  if (Q_UNLIKELY(d->engineRequest->status & EngineRequest::Finalized)) {
363  qCWarning(CUTELYST_ASYNC) << "Trying to async attach to a finalized request! Skipping...";
364  return;
365  }
366 
367  if (d->engineRequest->status & EngineRequest::Async) {
368  while (d->asyncAction < d->pendingAsync.size()) {
369  Component *action = d->pendingAsync[d->asyncAction++];
370  const bool ret = execute(action);
371 
372  if (d->actionRefCount) {
373  return;
374  }
375 
376  if (!ret) {
377  break; // we are finished
378  }
379  }
380 
381  Q_EMIT d->app->afterDispatch(this);
382 
383  finalize();
384  }
385 }
386 
388 {
389  Q_D(Context);
390  return d->dispatcher->forward(this, action);
391 }
392 
393 bool Context::forward(const QString &action)
394 {
395  Q_D(Context);
396  return d->dispatcher->forward(this, action);
397 }
398 
399 Action *Context::getAction(const QString &action, const QString &ns) const
400 {
401  Q_D(const Context);
402  return d->dispatcher->getAction(action, ns);
403 }
404 
405 QVector<Action *> Context::getActions(const QString &action, const QString &ns) const
406 {
407  Q_D(const Context);
408  return d->dispatcher->getActions(action, ns);
409 }
410 
411 QVector<Cutelyst::Plugin *> Context::plugins() const
412 {
413  Q_D(const Context);
414  return d->plugins;
415 }
416 
418 {
419  Q_D(Context);
420  Q_ASSERT_X(code, "Context::execute", "trying to execute a null Cutelyst::Component");
421 
422  static int recursion = qEnvironmentVariableIsSet("RECURSION") ? qEnvironmentVariableIntValue("RECURSION") : 1000;
423  if (d->stack.size() >= recursion) {
424  QString msg = QStringLiteral("Deep recursion detected (stack size %1) calling %2, %3")
425  .arg(QString::number(d->stack.size()), code->reverse(), code->name());
426  error(msg);
427  setState(false);
428  return false;
429  }
430 
431  bool ret;
432  d->stack.push(code);
433 
434  if (d->stats) {
435  const QString statsInfo = d->statsStartExecute(code);
436 
437  ret = code->execute(this);
438 
439  // The request might finalize execution before returning
440  // so it's wise to check for d->stats again
441  if (d->stats && !statsInfo.isEmpty()) {
442  d->statsFinishExecute(statsInfo);
443  }
444  } else {
445  ret = code->execute(this);
446  }
447 
448  d->stack.pop();
449 
450  return ret;
451 }
452 
453 QLocale Context::locale() const noexcept
454 {
455  Q_D(const Context);
456  return d->locale;
457 }
458 
459 void Context::setLocale(const QLocale &locale)
460 {
461  Q_D(Context);
462  d->locale = locale;
463 }
464 
465 QVariant Context::config(const QString &key, const QVariant &defaultValue) const
466 {
467  Q_D(const Context);
468  return d->app->config(key, defaultValue);
469 }
470 
471 QVariantMap Context::config() const noexcept
472 {
473  Q_D(const Context);
474  return d->app->config();
475 }
476 
477 QString Context::translate(const char *context, const char *sourceText, const char *disambiguation, int n) const
478 {
479  Q_D(const Context);
480  return d->app->translate(d->locale, context, sourceText, disambiguation, n);
481 }
482 
484 {
485  Q_D(Context);
486 
487  if (Q_UNLIKELY(d->engineRequest->status & EngineRequest::Finalized)) {
488  qCWarning(CUTELYST_CORE) << "Trying to finalize a finalized request! Skipping...";
489  return;
490  }
491 
492  if (d->stats) {
493  qCDebug(CUTELYST_STATS, "Response Code: %d; Content-Type: %s; Content-Length: %s",
494  d->response->status(),
495  qPrintable(d->response->headers().header(QStringLiteral("CONTENT_TYPE"), QStringLiteral("unknown"))),
496  qPrintable(d->response->headers().header(QStringLiteral("CONTENT_LENGTH"), QStringLiteral("unknown"))));
497 
498  const double enlapsed = d->engineRequest->elapsed.nsecsElapsed() / 1000000000.0;
499  QString average;
500  if (enlapsed == 0.0) {
501  average = QStringLiteral("??");
502  } else {
503  average = QString::number(1.0 / enlapsed, 'f');
504  average.truncate(average.size() - 3);
505  }
506  qCInfo(CUTELYST_STATS) << qPrintable(QStringLiteral("Request took: %1s (%2/s)\n%3")
507  .arg(QString::number(enlapsed, 'f'),
508  average,
509  QString::fromLatin1(d->stats->report())));
510  delete d->stats;
511  d->stats = nullptr;
512  }
513 
514  d->engineRequest->finalize();
515 }
516 
517 QString ContextPrivate::statsStartExecute(Component *code)
518 {
519  QString actionName;
520  // Skip internal actions
521  if (code->name().startsWith(u'_')) {
522  return actionName;
523  }
524 
525  actionName = code->reverse();
526 
527  if (qobject_cast<Action *>(code)) {
528  actionName.prepend(u'/');
529  }
530 
531  if (stack.size() > 2) {
532  actionName = u"-> " + actionName;
533  actionName = actionName.rightJustified(actionName.size() + stack.size() - 2, QLatin1Char(' '));
534  }
535 
536  stats->profileStart(actionName);
537 
538  return actionName;
539 }
540 
541 void ContextPrivate::statsFinishExecute(const QString &statsInfo)
542 {
543  stats->profileEnd(statsInfo);
544 }
545 
546 void Context::stash(const QVariantHash &unite)
547 {
548  Q_D(Context);
549  auto it = unite.constBegin();
550  while (it != unite.constEnd()) {
551  d->stash.insert(it.key(), it.value());
552  ++it;
553  }
554 }
555 
556 #include "moc_context.cpp"
557 #include "moc_context_p.cpp"
This class represents a Cutelyst Action.
Definition: action.h:35
virtual qint8 numberOfCaptures() const noexcept
Definition: action.cpp:128
The Cutelyst Application.
Definition: application.h:43
Headers & defaultHeaders() noexcept
Definition: application.cpp:82
The Cutelyst Component base class.
Definition: component.h:26
bool execute(Context *c)
Definition: component.cpp:62
QString name() const
Definition: component.cpp:31
QString reverse() const
Definition: component.cpp:43
The Cutelyst Context.
Definition: context.h:39
QVector< Action * > getActions(const QString &action, const QString &ns={}) const
Definition: context.cpp:405
QStringList errors() const noexcept
Returns a list of errors that were defined.
Definition: context.cpp:67
bool forward(Component *component)
Definition: context.cpp:387
QUrl uriFor(const QString &path=QString(), const QStringList &args=QStringList(), const ParamsMultiMap &queryValues=ParamsMultiMap()) const
Definition: context.cpp:236
QVector< Plugin * > plugins() const
Definition: context.cpp:411
Context(Application *app)
Constructs a new DUMMY Context object that is child of Application This currently is experimental to ...
Definition: context.cpp:30
Action * getAction(const QString &action, const QString &ns={}) const
Definition: context.cpp:399
void detach(Action *action=nullptr)
Definition: context.cpp:339
QStack< Component * > stack() const noexcept
Definition: context.cpp:230
QVariantHash & stash()
Definition: context.cpp:188
QLocale locale() const noexcept
Definition: context.cpp:453
void setState(bool state) noexcept
Sets the state of the current executed action, setting to false will make the dispatcher skip non pro...
Definition: context.cpp:79
Response * res() const noexcept
Definition: context.cpp:103
QString translate(const char *context, const char *sourceText, const char *disambiguation=nullptr, int n=-1) const
Definition: context.cpp:477
void setStash(const QString &key, const QVariant &value)
Definition: context.cpp:218
void finalize()
finalize the request right away this is automatically called at the end of the actions chain
Definition: context.cpp:483
bool stashRemove(const QString &key)
Definition: context.cpp:212
QVariant stashTake(const QString &key)
Definition: context.cpp:206
void attachAsync()
attachAsync
Definition: context.cpp:355
void setLocale(const QLocale &locale)
Definition: context.cpp:459
View * customView() const noexcept
Definition: context.cpp:163
bool detached() const noexcept
Definition: context.cpp:333
View * view(const QString &name) const
Definition: context.cpp:169
QUrl uriForAction(const QString &path, const QStringList &captures=QStringList(), const QStringList &args=QStringList(), const ParamsMultiMap &queryValues=ParamsMultiMap()) const
Definition: context.cpp:318
Dispatcher * dispatcher() const noexcept
Definition: context.cpp:139
Application * app() const noexcept
Definition: context.cpp:91
void detachAsync() noexcept
Definition: context.cpp:349
bool execute(Component *code)
Definition: context.cpp:417
bool setCustomView(const QString &name)
Definition: context.cpp:181
Engine * engine() const noexcept
Definition: context.cpp:85
bool error() const noexcept
Returns true if an error was set.
Definition: context.cpp:50
Response * response() const noexcept
Definition: context.cpp:97
Cutelyst Controller base class
Definition: controller.h:90
The Cutelyst Dispatcher.
Definition: dispatcher.h:28
The Cutelyst Engine.
Definition: engine.h:21
QIODevice * body() const
Definition: request.cpp:179
Cutelyst View abstract view component
Definition: view.h:22
The Cutelyst namespace holds all public Cutelyst API.
Definition: Mainpage.dox:8
QMultiMap< QString, QString > ParamsMultiMap