cutelyst 5.0.0
A C++ Web Framework built on top of Qt, using the simple approach of Catalyst (Perl) framework.
dispatchtypechained.cpp
1/*
2 * SPDX-FileCopyrightText: (C) 2015-2022 Daniel Nicoletti <dantti12@gmail.com>
3 * SPDX-License-Identifier: BSD-3-Clause
4 */
5#include "actionchain.h"
6#include "common.h"
7#include "context.h"
8#include "dispatchtypechained_p.h"
9#include "utils.h"
10
11#include <QtCore/QUrl>
12
13using namespace Cutelyst;
14using namespace Qt::Literals::StringLiterals;
15
17 : DispatchType(parent)
18 , d_ptr(new DispatchTypeChainedPrivate)
19{
20}
21
26
28{
29 Q_D(const DispatchTypeChained);
30
31 QByteArray buffer;
32 Actions endPoints = d->endPoints;
33 std::ranges::sort(endPoints,
34 [](Action *a, Action *b) -> bool { return a->reverse() < b->reverse(); });
35
37 QVector<QStringList> unattachedTable;
38 for (Action *endPoint : std::as_const(endPoints)) {
39 QStringList parts;
40 if (endPoint->numberOfArgs() == -1) {
41 parts.append(QLatin1String("..."));
42 } else {
43 for (int i = 0; i < endPoint->numberOfArgs(); ++i) {
44 parts.append(QLatin1String("*"));
45 }
46 }
47
49 QString extra = DispatchTypeChainedPrivate::listExtraHttpMethods(endPoint);
50 QString consumes = DispatchTypeChainedPrivate::listExtraConsumes(endPoint);
51 ActionList parents;
52 Action *current = endPoint;
53 while (current) {
54 for (int i = 0; i < current->numberOfCaptures(); ++i) {
55 parts.prepend(QLatin1String("*"));
56 }
57
58 const auto attributes = current->attributes();
59 const QStringList pathParts = attributes.values(QLatin1String("PathPart"));
60 for (const QString &part : pathParts) {
61 if (!part.isEmpty()) {
62 parts.prepend(part);
63 }
64 }
65
66 parent = attributes.value(QLatin1String("Chained"));
67 current = d->actions.value(parent);
68 if (current) {
69 parents.prepend(current);
70 }
71 }
72
73 if (parent.compare(u"/") != 0) {
74 QStringList row;
75 if (parents.isEmpty()) {
76 row.append(QLatin1Char('/') + endPoint->reverse());
77 } else {
78 row.append(QLatin1Char('/') + parents.first()->reverse());
79 }
80 row.append(parent);
81 unattachedTable.append(row);
82 continue;
83 }
84
86 for (Action *p : parents) {
87 QString name = QLatin1Char('/') + p->reverse();
88
89 QString extraHttpMethod = DispatchTypeChainedPrivate::listExtraHttpMethods(p);
90 if (!extraHttpMethod.isEmpty()) {
91 name.prepend(extraHttpMethod + QLatin1Char(' '));
92 }
93
94 const auto attributes = p->attributes();
95 auto it = attributes.constFind(QLatin1String("CaptureArgs"));
96 if (it != attributes.constEnd()) {
97 name.append(QLatin1String(" (") + it.value() + QLatin1Char(')'));
98 } else {
99 name.append(QLatin1String(" (0)"));
100 }
101
102 QString ct = DispatchTypeChainedPrivate::listExtraConsumes(p);
103 if (!ct.isEmpty()) {
104 name.append(QLatin1String(" :") + ct);
105 }
106
107 if (p != parents[0]) {
108 name = QLatin1String("-> ") + name;
109 }
110
111 rows.append({QString(), name});
112 }
113
114 QString line;
115 if (!rows.isEmpty()) {
116 line.append(QLatin1String("=> "));
117 }
118 if (!extra.isEmpty()) {
119 line.append(extra + QLatin1Char(' '));
120 }
121 line.append(QLatin1Char('/') + endPoint->reverse());
122 if (endPoint->numberOfArgs() == -1) {
123 line.append(QLatin1String(" (...)"));
124 } else {
125 line.append(QLatin1String(" (") + QString::number(endPoint->numberOfArgs()) +
126 QLatin1Char(')'));
127 }
128
129 if (!consumes.isEmpty()) {
130 line.append(QLatin1String(" :") + consumes);
131 }
132 rows.append({QString(), line});
133
134 rows[0][0] = QLatin1Char('/') + parts.join(QLatin1Char('/'));
135 paths.append(rows);
136 }
137
139
140 if (!paths.isEmpty()) {
141 out << Utils::buildTable(paths,
142 {QLatin1String("Path Spec"), QLatin1String("Private")},
143 QLatin1String("Loaded Chained actions:"));
144 }
145
146 if (!unattachedTable.isEmpty()) {
147 out << Utils::buildTable(unattachedTable,
148 {QLatin1String("Private"), QLatin1String("Missing parent")},
149 QLatin1String("Unattached Chained actions:"));
150 }
151
152 return buffer;
153}
154
157{
158 if (!args.isEmpty()) {
159 return NoMatch;
160 }
161
162 Q_D(const DispatchTypeChained);
163
164 const BestActionMatch ret = d->recurseMatch(args.size(), u"/"_s, path.mid(1).split(u'/'));
165 const ActionList chain = ret.actions;
166 if (ret.isNull || chain.isEmpty()) {
167 return NoMatch;
168 }
169
170 QStringList decodedArgs;
171 const auto parts = ret.parts;
172 for (const auto &arg : parts) {
173 QString aux = arg.toString();
174 decodedArgs.append(Utils::decodePercentEncoding(&aux));
175 }
176
177 auto action = new ActionChain(chain, c);
178 Request *request = c->request();
179 request->setArguments(decodedArgs);
180 QStringList captures;
181 for (const auto a : ret.captures) {
182 captures.append(a.toString());
183 }
184 request->setCaptures(captures);
185 request->setMatch(QLatin1Char('/') + action->reverse());
186 setupMatchedAction(c, action);
187
188 return ExactMatch;
189}
190
192{
194
195 auto attributes = action->attributes();
196 const QStringList chainedList = attributes.values(QLatin1String("Chained"));
197 if (chainedList.isEmpty()) {
198 return false;
199 }
200
201 if (chainedList.size() > 1) {
202 qCCritical(CUTELYST_DISPATCHER_CHAINED)
203 << "Multiple Chained attributes not supported registering" << action->reverse();
204 return false;
205 }
206
207 const QString &chainedTo = chainedList.first();
208 if (chainedTo == u'/' + action->name()) {
209 qCCritical(CUTELYST_DISPATCHER_CHAINED)
210 << "Actions cannot chain to themselves registering /" << action->name();
211 return false;
212 }
213
214 const QStringList pathPart = attributes.values(QLatin1String("PathPart"));
215
216 QString part = action->name();
217
218 if (pathPart.size() == 1 && !pathPart[0].isEmpty()) {
219 part = pathPart[0];
220 } else if (pathPart.size() > 1) {
221 qCCritical(CUTELYST_DISPATCHER_CHAINED)
222 << "Multiple PathPart attributes not supported registering" << action->reverse();
223 return false;
224 }
225
226 if (part.startsWith(QLatin1Char('/'))) {
227 qCCritical(CUTELYST_DISPATCHER_CHAINED)
228 << "Absolute parameters to PathPart not allowed registering" << action->reverse();
229 return false;
230 }
231
232 attributes.replace(QStringLiteral("PathPart"), part);
233 action->setAttributes(attributes);
234
235 auto &childrenOf = d->childrenOf[chainedTo][part];
236 childrenOf.insert(childrenOf.begin(), action);
237
238 d->actions[QLatin1Char('/') + action->reverse()] = action;
239
240 if (!d->checkArgsAttr(action, QLatin1String("Args")) ||
241 !d->checkArgsAttr(action, QLatin1String("CaptureArgs"))) {
242 return false;
243 }
244
245 if (attributes.contains(QLatin1String("Args")) &&
246 attributes.contains(QLatin1String("CaptureArgs"))) {
247 qCCritical(CUTELYST_DISPATCHER_CHAINED)
248 << "Combining Args and CaptureArgs attributes not supported registering"
249 << action->reverse();
250 return false;
251 }
252
253 if (!attributes.contains(QLatin1String("CaptureArgs"))) {
254 d->endPoints.push_back(action);
255 }
256
257 return true;
258}
259
261{
262 Q_D(const DispatchTypeChained);
263
264 QString ret;
265 const ParamsMultiMap attributes = action->attributes();
266 if (!(attributes.contains(QStringLiteral("Chained")) &&
267 !attributes.contains(QStringLiteral("CaptureArgs")))) {
268 qCWarning(CUTELYST_DISPATCHER_CHAINED)
269 << "uriForAction: action is not an end point" << action;
270 return ret;
271 }
272
274 QStringList localCaptures = captures;
275 QStringList parts;
276 Action *curr = action;
277 while (curr) {
278 const ParamsMultiMap curr_attributes = curr->attributes();
279 if (curr_attributes.contains(QStringLiteral("CaptureArgs"))) {
280 if (localCaptures.size() < curr->numberOfCaptures()) {
281 // Not enough captures
282 qCWarning(CUTELYST_DISPATCHER_CHAINED)
283 << "uriForAction: not enough captures" << curr->numberOfCaptures()
284 << captures.size();
285 return ret;
286 }
287
288 parts = localCaptures.mid(localCaptures.size() - curr->numberOfCaptures()) + parts;
289 localCaptures = localCaptures.mid(0, localCaptures.size() - curr->numberOfCaptures());
290 }
291
292 const QString pp = curr_attributes.value(QStringLiteral("PathPart"));
293 if (!pp.isEmpty()) {
294 parts.prepend(pp);
295 }
296
297 parent = curr_attributes.value(QStringLiteral("Chained"));
298 curr = d->actions.value(parent);
299 }
300
301 if (parent.compare(u"/") != 0) {
302 // fail for dangling action
303 qCWarning(CUTELYST_DISPATCHER_CHAINED) << "uriForAction: dangling action" << parent;
304 return ret;
305 }
306
307 if (!localCaptures.isEmpty()) {
308 // fail for too many captures
309 qCWarning(CUTELYST_DISPATCHER_CHAINED)
310 << "uriForAction: too many captures" << localCaptures;
311 return ret;
312 }
313
314 ret = QLatin1Char('/') + parts.join(QLatin1Char('/'));
315 return ret;
316}
317
319{
320 Q_D(const DispatchTypeChained);
321
322 // Do not expand action if action already is an ActionChain
323 if (qobject_cast<ActionChain *>(action)) {
324 return action;
325 }
326
327 // The action must be chained to something
328 if (!action->attributes().contains(QStringLiteral("Chained"))) {
329 return nullptr;
330 }
331
332 ActionList chain;
333 Action *curr = action;
334
335 while (curr) {
336 chain.prepend(curr);
337 const QString parent = curr->attribute(QStringLiteral("Chained"));
338 curr = d->actions.value(parent);
339 }
340
341 return new ActionChain(chain, const_cast<Context *>(c));
342}
343
345{
346 Q_D(const DispatchTypeChained);
347
348 if (d->actions.isEmpty()) {
349 return false;
350 }
351
352 // Optimize end points
353
354 return true;
355}
356
357BestActionMatch DispatchTypeChainedPrivate::recurseMatch(int reqArgsSize,
358 const QString &parent,
359 const QList<QStringView> &pathParts) const
360{
361 BestActionMatch bestAction;
362 const auto it = childrenOf.constFind(parent);
363 if (it == childrenOf.constEnd()) {
364 return bestAction;
365 }
366
367 const StringActionsMap &children = it.value();
368 QStringList keys = children.keys();
369 std::ranges::sort(keys, [](const QString &a, const QString &b) -> bool {
370 // action2 then action1 to try the longest part first
371 return b.size() < a.size();
372 });
373
374 for (const QString &tryPart : std::as_const(keys)) {
375 auto parts = pathParts;
376 if (!tryPart.isEmpty()) {
377 // We want to count the number of parts a split would give
378 // and remove the number of parts from tryPart
379 int tryPartCount = tryPart.count(u'/') + 1;
380 const auto possibleParts = parts.mid(0, tryPartCount);
381
382 QString possiblePartsString;
383 bool first = true;
384 for (const auto part : possibleParts) {
385 if (first) {
386 possiblePartsString = part.toString();
387 first = false;
388 } else {
389 possiblePartsString.append(u'/' + part);
390 }
391 }
392
393 if (tryPart != possiblePartsString) {
394 continue;
395 }
396 parts = parts.mid(tryPartCount);
397 }
398
399 const Actions tryActions = children.value(tryPart);
400 for (Action *action : tryActions) {
401 const ParamsMultiMap attributes = action->attributes();
402 if (attributes.contains(u"CaptureArgs"_s)) {
403 const auto captureCount = action->numberOfCaptures();
404 // Short-circuit if not enough remaining parts
405 if (parts.size() < captureCount) {
406 continue;
407 }
408
409 // strip CaptureArgs into list
410 const auto captures = parts.mid(0, captureCount);
411
412 // check if the action may fit, depending on a given test by the app
413 if (!action->matchCaptures(captures.size())) {
414 continue;
415 }
416
417 const auto localParts = parts.mid(captureCount);
418
419 // try the remaining parts against children of this action
420 const BestActionMatch ret =
421 recurseMatch(reqArgsSize, QLatin1Char('/') + action->reverse(), localParts);
422
423 // No best action currently
424 // OR The action has less parts
425 // OR The action has equal parts but less captured data (ergo more defined)
426 ActionList actions = ret.actions;
427 const auto actionCaptures = ret.captures;
428 const auto actionParts = ret.parts;
429 int bestActionParts = bestAction.parts.size();
430
431 if (!actions.isEmpty() &&
432 (bestAction.isNull || actionParts.size() < bestActionParts ||
433 (actionParts.size() == bestActionParts &&
434 actionCaptures.size() < bestAction.captures.size() &&
435 ret.n_pathParts > bestAction.n_pathParts))) {
436 actions.prepend(action);
437 int pathparts = attributes.value(u"PathPart"_s).count(u'/') + 1;
438 bestAction.actions = actions;
439 bestAction.captures = captures + actionCaptures;
440 bestAction.parts = actionParts;
441 bestAction.n_pathParts = pathparts + ret.n_pathParts;
442 bestAction.isNull = false;
443 }
444 } else {
445 if (!action->match(reqArgsSize + parts.size())) {
446 continue;
447 }
448
449 const QString argsAttr = attributes.value(u"Args"_s);
450 const int pathparts = attributes.value(u"PathPart"_s).count(u'/') + 1;
451 // No best action currently
452 // OR This one matches with fewer parts left than the current best action,
453 // And therefore is a better match
454 // OR No parts and this expects 0
455 // The current best action might also be Args(0),
456 // but we couldn't chose between then anyway so we'll take the last seen
457
458 if (bestAction.isNull || parts.size() < bestAction.parts.size() ||
459 (parts.isEmpty() && !argsAttr.isEmpty() && action->numberOfArgs() == 0)) {
460 bestAction.actions = {action};
461 bestAction.captures = {};
462 bestAction.parts = parts;
463 bestAction.n_pathParts = pathparts;
464 bestAction.isNull = false;
465 }
466 }
467 }
468 }
469
470 return bestAction;
471}
472
473bool DispatchTypeChainedPrivate::checkArgsAttr(Action *action, const QString &name) const
474{
475 const auto attributes = action->attributes();
476 if (!attributes.contains(name)) {
477 return true;
478 }
479
480 const QStringList values = attributes.values(name);
481 if (values.size() > 1) {
482 qCCritical(CUTELYST_DISPATCHER_CHAINED)
483 << "Multiple" << name << "attributes not supported registering" << action->reverse();
484 return false;
485 }
486
487 QString args = values[0];
488 bool ok;
489 if (!args.isEmpty() && args.toInt(&ok) < 0 && !ok) {
490 qCCritical(CUTELYST_DISPATCHER_CHAINED)
491 << "Invalid" << name << "(" << args << ") for action" << action->reverse() << "(use '"
492 << name << "' or '" << name << "(<number>)')";
493 return false;
494 }
495
496 return true;
497}
498
499QString DispatchTypeChainedPrivate::listExtraHttpMethods(Action *action)
500{
501 QString ret;
502 const auto attributes = action->attributes();
503 if (attributes.contains(QLatin1String("HTTP_METHODS"))) {
504 const QStringList extra = attributes.values(QLatin1String("HTTP_METHODS"));
505 ret = extra.join(QLatin1String(", "));
506 }
507 return ret;
508}
509
510QString DispatchTypeChainedPrivate::listExtraConsumes(Action *action)
511{
512 QString ret;
513 const auto attributes = action->attributes();
514 if (attributes.contains(QLatin1String("CONSUMES"))) {
515 const QStringList extra = attributes.values(QLatin1String("CONSUMES"));
516 ret = extra.join(QLatin1String(", "));
517 }
518 return ret;
519}
520
521#include "moc_dispatchtypechained.cpp"
Holds a chain of Cutelyst actions.
Definition actionchain.h:26
This class represents a Cutelyst Action.
Definition action.h:35
void setAttributes(const ParamsMultiMap &attributes)
Definition action.cpp:81
virtual qint8 numberOfCaptures() const
Definition action.cpp:131
ParamsMultiMap attributes() const noexcept
Definition action.cpp:69
QString attribute(const QString &name, const QString &defaultValue={}) const
Definition action.cpp:75
QString reverse() const noexcept
Definition component.cpp:45
QString name() const noexcept
Definition component.cpp:33
The Cutelyst Context.
Definition context.h:42
Request * request
Definition context.h:71
Describes a chained dispatch type.
MatchType match(Context *c, QStringView path, const QStringList &args) const override
QString uriForAction(Action *action, const QStringList &captures) const override
QByteArray list() const override
bool registerAction(Action *action) override
Action * expandAction(const Context *c, Action *action) const final
DispatchTypeChained(QObject *parent=nullptr)
Abstract class to described a dispatch type.
void setupMatchedAction(Context *c, Action *action) const
A request.
Definition request.h:42
void setCaptures(const QStringList &captures)
Definition request.cpp:168
void setArguments(const QStringList &arguments)
Definition request.cpp:156
void setMatch(const QString &match)
Definition request.cpp:144
The Cutelyst namespace holds all public Cutelyst API.
void append(QList::parameter_type value)
qsizetype count() const const
T & first()
bool isEmpty() const const
QList< T > mid(qsizetype pos, qsizetype length) const const
void prepend(QList::parameter_type value)
qsizetype size() const const
bool contains(const Key &key) const const
T value(const Key &key, const T &defaultValue) const const
QList< T > values() const const
QObject * parent() const const
QString & append(QChar ch)
bool isEmpty() const const
QString mid(qsizetype position, qsizetype n) const const
QString number(double n, char format, int precision)
QString & prepend(QChar ch)
void push_back(QChar ch)
QString & replace(QChar before, QChar after, Qt::CaseSensitivity cs)
qsizetype size() const const
bool startsWith(QChar c, Qt::CaseSensitivity cs) const const
int toInt(bool *ok, int base) const const
QString join(QChar separator) const const
QStringView mid(qsizetype start, qsizetype length) const const
QList< QStringView > split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const const