clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,9 @@
Bipsum
Booh
Brava
Feigenbaum
meny
multiresponse
rels
reqs
subreqs
+52
View File
@@ -0,0 +1,52 @@
################
# DrupalCI GitLabCI template
#
# Gitlab-ci.yml to replicate DrupalCI testing for Contrib
#
# With thanks to:
# * The GitLab Acceleration Initiative participants
# * DrupalSpoons
################
################
# Guidelines
#
# This template is designed to give any Contrib maintainer everything they need to test, without requiring modification. It is also designed to keep up to date with Core Development automatically through the use of include files that can be centrally maintained.
#
# However, you can modify this template if you have additional needs for your project.
################
################
# Includes
#
# Additional configuration can be provided through includes.
# One advantage of include files is that if they are updated upstream, the changes affect all pipelines using that include.
#
# Includes can be overridden by re-declaring anything provided in an include, here in gitlab-ci.yml
# https://docs.gitlab.com/ee/ci/yaml/includes.html#override-included-configuration-values
################
include:
################
# DrupalCI includes:
# As long as you include this, any future includes added by the Drupal Association will be accessible to your pipelines automatically.
# View these include files at https://git.drupalcode.org/project/gitlab_templates/
################
- project: $_GITLAB_TEMPLATES_REPO
ref: $_GITLAB_TEMPLATES_REF
file:
- '/includes/include.drupalci.main.yml'
- '/includes/include.drupalci.variables.yml'
- '/includes/include.drupalci.workflows.yml'
################
# Pipeline configuration variables
#
# These are the variables provided to the Run Pipeline form that a user may want to override.
#
# Docs at https://git.drupalcode.org/project/gitlab_templates/-/blob/1.0.x/includes/include.drupalci.variables.yml
################
variables:
OPT_IN_TEST_PREVIOUS_MINOR: 1
OPT_IN_TEST_NEXT_MINOR: 1
OPT_IN_TEST_NEXT_MAJOR: 1
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+300
View File
@@ -0,0 +1,300 @@
# Request Blueprint
## Request format
### Basic requests
A request blueprint is a document containing a list of HTTP requests that a
client can send to a server. Once the server receives the request blueprint, it
**MUST** process all the HTTP requests in the blueprint to produce a
single response containing the information of the responses to the blueprint
requests.
The request that sends the request blueprint is referenced as the master request
or the root request.
An example of a blueprint could look like this:
```json
[
{
"requestId": "req-1",
"uri": "/restaurants/886e3b86-fa53-4bb3-b2c2-3ed544f1cd51?fields=title",
"action": "view",
"headers": {
"Accept": "application/json"
}
},
{
"requestId": "req-2",
"uri": "/deals?page[limit]=5",
"action": "view",
"headers": {
"Accept": "application/vnd.api+json"
}
},
{
"requestId": "req-3",
"uri": "/stats",
"action": "create",
"body": "{\"visitor\":\"anonymous\"}",
"headers": {
"Accept": "application/json",
"Content-Type": "application/json"
}
}
]
```
The blueprint above represents three different requests that may be run in
parallel by the server. These requests could transform into the following
parallel HTTP requests.
```http
GET /restaurants/886e3b86-fa53-4bb3-b2c2-3ed544f1cd51 HTTP/1.1
Host: example.org
Accept: application/vnd.api+json
```
```http
GET /restaurants/886e3b86-fa53-4bb3-b2c2-3ed544f1cd51 HTTP/1.1
Host: example.org
Accept: application/vnd.api+json
```
```http
POST /stats HTTP/1.1
Host: example.org
Accept: application/json
Content-Type: application/json
{"visitor":"anonymous"}
```
### Payload format
You **MUST** provide a `Content-Type` header when sending a request to the front
controller that processes the request blueprint. The content type header will
determine what format is used in the blueprint. All the examples in this
document assume `application/json` as the content type.
You **MAY** send the blueprint document as the payload in a `POST` request.
Alternatively, you **MAY** also send it in a `GET` request as a [percent
encoded](https://tools.ietf.org/html/rfc3986#section-2.1) string in a query
string parameter with the name of `query`.
The blueprint document **MUST** be an array of subrequests. Each one of these
subrequests **SHOULD** contain at least the following properties:
* `action`: this indicates the type of action this subrequest will execute.
Common values for this property are `view`, `create`, `update`, `replace`,
`delete`, `exists` and `discover`.
* `uri`: the URI for the subrequest.
Additionally the payload for a subrequest **MAY** contain the following
properties:
* `requestId`: a unique identifier for the subrequest. This will be used to
match the subrequest with one of the partial responses.
* `body`: the serialized content of the body for the subrequest.
* `headers`: an object of key value pairs. Each key **MUST** be interpreted as
a header name for the subrequest, and the values as the header value.
* `waitFor`: contains the array of request IDs from another request. Indicates
that the current subrequest depends on the other subrequest. When this
property is present, the that particular subrequest cannot be processed
until the referenced request has generated a response.
### Sequential requests
Many times it is necessary to use the information of previous requests in order
to build the correct request. That happens because a given request has a
dependency some other requests to be resolved first. That use case is solved by
request dependencies and by response pointers.
#### Request dependency
Any request can express a dependency on the response of a previous request. To
do so such request **SHOULD** express the dependency in the `waitFor` key. The
contents of this property **WILL** contain the request ID this request depends
on.
One subrequest **CAN** only indicate a dependency to one other subrequest. If a
subrequest depends on a collection of subrequests at the same time, then the
user **MAY** turn that collection into a request blueprint. That will to convert
that collection into a single subrequest that can be waited for.
#### Response embedding
Some subrequests need information that is only made available when a previous
subrequest has been processed and turned into a response. In that situation a
subrequest **CAN** contain a replacement token that **MUST** be resolved from
responses to previous subrequests in the same blueprint.
The format of the replacement token is:
```
{{/<request-id>.<location>@<json-path-expression>}}
```
The replacement data will be extracted from the response to the request
indicated by the request ID in the replacement token. The specific data in that
response to be embedded will be selected using a json path. If the JSON path
expression resolves more than one result, then multiple responses will be
generated for that single request.
A data pointer is a string that specifies what part of the referenced response
should be embedded in place of the token. The embedded data **SHOULD** be
serialized into a string according to the content type specified for the master
request.
When the content type of the master request is set to `application/json` then
the data pointer **SHOULD** conform to the JSON pointer specification [RFC
6901](https://tools.ietf.org/html/rfc6901). If the content type is set to
`application/xml` then the data pointer **SHOULD** be an XPath 2.0 compatible
with the [W3C specification](https://www.w3.org/TR/xpath20).
Replacement tokens **SHOULD NOT** be used in the `requestId` or `waitFor`
properties.
#### Example
The following example shows how you can make use of the response embedding in
the request blueprint to express dependencies.
```json
[
{
"requestId": "req-1",
"uri": "/restaurants/886e3b86-fa53-4bb3-b2c2-3ed544f1cd51&fields=menus",
"action": "view",
"headers": {
"Accept": "application/json"
}
},
{
"requestId": "req-2",
"waitFor": ["req-1"],
"uri": "/menus/{{req-1.body@$.rels.meny.id}}",
"action": "view",
"headers": {
"Accept": "application/json"
}
},
{
"requestId": "req-3",
"waitFor": ["req-2"],
"uri": "/menus/{{req-1.body@$.rels.meny.id}}/courses/{{req-2.body@$.mainCourse.id}}",
"action": "view",
"headers": {
"Accept": "application/json"
}
}
]
```
This example shows how the request for the restaurant menu needs information in
the body from the request to the response to _req-1_. It also shows that
_req-3_ depends on both _req-1_ and _req-2_ to compose the request.
# Response format
Once all the requests have been processed and the corresponding responses have
been generated, the server **MUST** give a single response to the master
request containing the responses to all subrequests.
The response **MUST** use the 207 response code for multiple status, since each
partial response will specify the status for their requests.
## HTML Response
The default response format is HTML.
HTML responses will use the `multipart/related` MIME type as specified in
[RFC 2387](https://tools.ietf.org/html/rfc2387):
```http
Content-Type: multipart/related; boundary="e43889"; type=application/json
```
A response to the blueprint above could look like:
```http
--e43889
Cache-Control: no-cache
Content-Id: <req-1>
Content-Type: application/json
Status: 200
{"attrs": {"name": "Foo restaurant"}, "rels": {"menu": {"id": "1234"}}}
--e43889
Cache-Control: no-cache
Content-Id: <req-2>
Content-Type: application/json
Status: 200
{"mainCourse": {"id": "meat-pie"}, "desert": {"id": "9876"}}
--e43889
Cache-Control: no-cache
Content-Id: <req-3>
Content-Type: application/vnd.api+json
Status: 200
{"ingredients": ["meat", "crust"]}
--e43889--
```
## JSON Response
A JSON response can be requested by specifying the JSON format with
`?_format=json`.
The response will be a JSON object containing each subrequest response keyed by
the specified `requestId`.
A response to the blueprint above could look like:
```json
{
"req-1": {
"headers": {
"cache-control": [
"no-cache"
],
"content-id": [
"<req-1>"
],
"content-type": [
"application/json"
],
"status": [
200
]
},
"body": "{\"attrs\": {\"name\": \"Foo restaurant\"}, \"rels\": {\"menu\":{\"id\":\"1234\"}}}"
},
"req-2": {
"headers": {
"cache-control": [
"no-cache"
],
"content-id": [
"<req-2>"
],
"content-type": [
"application/json"
],
"status": [
200
]
},
"body": "{\"mainCourse\": {\"id\": \"meat-pie\"}, \"desert\": {\"id\":\"9876\"}}"
},
"req-3": {
"headers": {
"cache-control": [
"no-cache"
],
"content-id": [
"<req-3>"
],
"content-type": [
"application/vnd.api+json"
],
"status": [
200
]
},
"body": "{\"ingredients\": [\"meat\", \"crust\"]}"
}
}
```
+20
View File
@@ -0,0 +1,20 @@
{
"name": "drupal/subrequests",
"description": "Add a front controller that you can use to make subrequests.",
"type": "drupal-module",
"require": {
"drupal/core": "^10 || ^11",
"galbar/jsonpath": "^1.0"
},
"require-dev": {
"justinrainbow/json-schema": "^5.2"
},
"license": "GPL-2.0+",
"authors": [
{
"name": "Mateu Aguiló Bosch",
"email": "[email protected]"
}
],
"minimum-stability": "dev"
}
+73
View File
@@ -0,0 +1,73 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Subrequests format",
"description": "Describes the subrequests payload format.",
"type": "array",
"items": {
"$ref": "#/definitions/subrequest"
},
"definitions": {
"subrequest": {
"title": "Subrequest",
"description": "Contains all the necessary information to make the request.",
"type": "object",
"required": [
"action",
"uri"
],
"additionalProperties": false,
"properties": {
"action": {
"title": "Action",
"description": "The action intended for the request. Each action can resolve into a different HTTP method.",
"type": "string",
"enum": [
"view",
"create",
"update",
"replace",
"delete",
"exists",
"discover",
"noop"
]
},
"uri": {
"title": "URI",
"description": "The URI where to make the subrequest.",
"type": "string"
},
"requestId": {
"title": "Request ID",
"description": "ID other requests can use to reference this request.",
"type": "string"
},
"body": {
"title": "Body",
"description": "The JSON encoded body payload for HTTP requests send a body.",
"type": "string"
},
"headers": {
"title": "Headers",
"description": "HTTP headers to be sent with the request.",
"type": "object",
"additionalProperties": true,
"patternProperties": {
".*": {
"type": "string"
}
}
},
"waitFor": {
"title": "Parent ID",
"description": "ID of other requests that this request depends on.",
"type": "array",
"items": {
"type": "string",
"description": "ID of another request that is a dependency for this one."
}
}
}
}
}
}
@@ -0,0 +1,130 @@
<?php
namespace Drupal\subrequests\Blueprint;
use Drupal\Core\Cache\CacheableResponse;
use Drupal\Core\Cache\CacheableResponseInterface;
use Drupal\subrequests\SubrequestsTree;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Serializer;
/**
* Manages the blueprint.
*/
class BlueprintManager {
/**
* The deserializer.
*
* @var \Symfony\Component\Serializer\SerializerInterface
*/
protected $serializer;
/**
* {@inheritDoc}
*/
public function __construct(Serializer $serializer) {
$this->serializer = $serializer;
}
/**
* Takes the user input and returns a subrequest tree ready for execution.
*
* @param string $input
* The input from the user.
* @param \Symfony\Component\HttpFoundation\Request $request
* The input from the user.
*
* @return \Drupal\subrequests\SubrequestsTree
* Parsed subrequest tree.
*/
public function parse($input, Request $request) {
/** @var \Drupal\subrequests\SubrequestsTree $output */
$output = $this->serializer
->deserialize($input, SubrequestsTree::class, 'json');
$output->setMasterRequest($request);
// Forward the Host header to place nice with decoupled routers.
$this->forwardHeader('host', $request, $output);
return $output;
}
/**
* Combines the responses of blueprint.
*
* @param \Symfony\Component\HttpFoundation\Response[] $responses
* The responses to combine.
* @param string $format
* The format to combine the responses on. Default is multipart/related.
*
* @return \Symfony\Component\HttpFoundation\Response
* The combined response with a 207.
*/
public function combineResponses(array $responses, $format) {
$context = [
'sub-content-type' => $this->negotiateSubContentType($responses),
];
// Set the content.
$normalized = $this->serializer->normalize($responses, $format, $context);
$response = new CacheableResponse($normalized['content'], 207, $normalized['headers']);
// Set the cacheability metadata.
$cacheable_responses = array_filter($responses, function ($response) {
return $response instanceof CacheableResponseInterface;
});
array_walk($cacheable_responses, function (CacheableResponseInterface $partial_response) use ($response) {
$response->addCacheableDependency($partial_response->getCacheableMetadata());
});
return $response;
}
/**
* Negotiates the sub Content-Type.
*
* Checks if all responses have the same Content-Type header. If they do, then
* it returns that one. If not, it defaults to 'application/json'.
*
* @param \Symfony\Component\HttpFoundation\Response[] $responses
* The responses.
*
* @return string
* The collective content type. 'application/json' if no conciliation is
* possible.
*/
protected function negotiateSubContentType($responses) {
$output = array_reduce($responses, function ($carry, Response $response) {
$ct = $response->headers->get('Content-Type');
if (!isset($carry)) {
$carry = $ct;
}
if ($carry !== $ct) {
$carry = 'application/json';
}
return $carry;
});
return $output ?: 'application/json';
}
/**
* Forward the master request's header to the subrequest.
*
* @param string $name
* The header name to forward.
* @param \Symfony\Component\HttpFoundation\Request $from
* The request to copy headers from.
* @param \Drupal\subrequests\SubrequestsTree $tree
* The target request to copy headers to.
*/
protected function forwardHeader($name, Request $from, SubrequestsTree $tree) {
foreach ($tree as $level) {
foreach ($level as $subrequest) {
/** @var \Drupal\subrequests\Subrequest $subrequest */
if (isset($subrequest->headers[$name])) {
continue;
}
$subrequest->headers[$name] = $from->headers->get($name);
}
}
}
}
@@ -0,0 +1,71 @@
<?php
namespace Drupal\subrequests\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\subrequests\Blueprint\BlueprintManager;
use Drupal\subrequests\SubrequestsManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Front controller to process Subrequests requests.
*/
class FrontController extends ControllerBase {
/**
* Blueprint manager.
*
* @var \Drupal\subrequests\Blueprint\BlueprintManager
*/
protected $blueprintManager;
/**
* Subrequest manager.
*
* @var \Drupal\subrequests\SubrequestsManager
*/
protected $subrequestsManager;
/**
* FrontController constructor.
*/
public function __construct(BlueprintManager $blueprint_manager, SubrequestsManager $subrequests_manager) {
$this->blueprintManager = $blueprint_manager;
$this->subrequestsManager = $subrequests_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('subrequests.blueprint_manager'),
$container->get('subrequests.subrequests_manager')
);
}
/**
* Controller handler.
*/
public function handle(Request $request) {
$data = '';
if ($request->getMethod() === Request::METHOD_POST) {
$data = $request->getContent();
}
elseif ($request->getMethod() === Request::METHOD_GET) {
$data = $request->query->get('query', '');
}
$tree = $this->blueprintManager->parse($data, $request);
$responses = $this->subrequestsManager->request($tree);
$master_request = $tree->getMasterRequest();
$output_format = $master_request->getRequestFormat();
if ($output_format === 'html') {
// Change the default format from html to multipart-related.
$output_format = 'multipart-related';
}
$master_request->getMimeType($output_format);
return $this->blueprintManager->combineResponses($responses, $output_format);
}
}
@@ -0,0 +1,401 @@
<?php
namespace Drupal\subrequests;
use Drupal\Component\Serialization\Json;
use JsonPath\JsonObject;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
/**
* Defines the json path replacer.
*/
class JsonPathReplacer {
/**
* Performs the JSON Path replacements in the whole batch.
*
* @param \Drupal\subrequests\Subrequest[] $batch
* The subrequests that contain replacement tokens.
* @param \Symfony\Component\HttpFoundation\Response[] $responses
* The accumulated responses from previous requests.
*
* @return \Drupal\subrequests\Subrequest[]
* An array of subrequests. Note that one input subrequest can generate N
* output subrequests. This is because JSON path expressions can return
* multiple values.
*/
public function replaceBatch(array $batch, array $responses) {
return array_reduce($batch, function (array $carry, Subrequest $subrequest) use ($responses) {
return array_merge(
$carry,
$this->replaceItem($subrequest, $responses)
);
}, []);
}
/**
* Searches for JSONPath tokens in the request and replaces them.
*
* @param \Drupal\subrequests\Subrequest $subrequest
* The list of requests that can contain tokens.
* @param \Symfony\Component\HttpFoundation\Response[] $pool
* The pool of responses that can content the values to replace.
*
* @returns \Drupal\subrequests\Subrequest[]
* The new list of requests. Note that if a JSONPath token yields many
* values then several replaced subrequests will be generated from the input
* subrequest.
*/
protected function replaceItem(Subrequest $subrequest, array $pool) {
$token_replacements = [
'uri' => $this->extractTokenReplacements($subrequest, 'uri', $pool),
'body' => $this->extractTokenReplacements($subrequest, 'body', $pool),
];
if (count($token_replacements['uri']) !== 0) {
return $this->replaceBatch(
$this->doReplaceTokensInLocation($token_replacements, $subrequest, 'uri'),
$pool
);
}
if (count($token_replacements['body']) !== 0) {
return $this->replaceBatch(
$this->doReplaceTokensInLocation($token_replacements, $subrequest, 'body'),
$pool
);
}
// If there are no replacements necessary, then just return the initial
// request.
$subrequest->_resolved = TRUE;
return [$subrequest];
}
/**
* Creates replacements for either the body or the URI.
*
* @param array $token_replacements
* Holds the info to replace text.
* @param \Drupal\subrequests\Subrequest $tokenized_subrequest
* The original copy of the subrequest.
* @param string $token_location
* Either 'body' or 'uri'.
*
* @returns \Drupal\subrequests\Subrequest[]
* The replaced subrequests.
*
* @private
*/
protected function doReplaceTokensInLocation(array $token_replacements, $tokenized_subrequest, $token_location) {
$replacements = [];
$tokens_per_content_id = $token_replacements[$token_location];
$index = 0;
// First figure out the different token resolutions and their token.
$grouped_by_token = [];
foreach ($tokens_per_content_id as $resolutions_per_token) {
foreach ($resolutions_per_token as $token => $resolutions) {
$grouped_by_token[] = array_map(function ($resolution) use ($token) {
return [
'token' => $token,
'value' => $resolution,
];
}, $resolutions);
}
}
// Then calculate the points.
$points = $this->getPoints($grouped_by_token);
foreach ($points as $point) {
// Clone the subrequest.
$cloned = clone $tokenized_subrequest;
$cloned->requestId = sprintf(
'%s#%s{%s}',
$tokenized_subrequest->requestId,
$token_location,
$index
);
$index++;
// Now replace all the tokens in the request member.
$token_subject = $this->serializeMember($token_location, $cloned->{$token_location});
foreach ($point as $replacement) {
// Do all the different replacements on the same subject.
$token_subject = $this->replaceTokenSubject(
$replacement['token'],
$replacement['value'],
$token_subject
);
}
$cloned->{$token_location} = $this->deserializeMember($token_location, $token_subject);
array_push($replacements, $cloned);
}
return $replacements;
}
/**
* Does the replacement on the token subject.
*
* @param string $token
* The thing to replace.
* @param string $value
* The thing to replace it with.
* @param string $token_subject
* The thing to replace it on.
*
* @returns string
* The replaced string.
*/
protected function replaceTokenSubject($token, $value, $token_subject) {
// Escape regular expression.
if (is_int($value) || is_float($value) || is_bool($value)) {
if (is_bool($value)) {
$value = $value ? 'true' : 'false';
}
$regexp = sprintf('/%s/', preg_quote("\"$token\"", '/'));
$token_subject = preg_replace($regexp, $value, $token_subject);
}
$regexp = sprintf('/%s/', preg_quote($token, '/'));
return preg_replace($regexp, $value, $token_subject);
}
/**
* Generates a list of sets of coordinates for the token replacements.
*
* Each point (coordinates set) end up creating a new clone of the tokenized
* subrequest.
*
* @param array $grouped_by_token
* Replacements grouped by token.
*
* @return array
* The coordinates sets.
*/
protected function getPoints($grouped_by_token) {
$current_group = array_shift($grouped_by_token);
// If this is not the last group, then call recursively.
if (empty($grouped_by_token)) {
return array_map(function ($item) {
return [$item];
}, $current_group);
}
$points = [];
foreach ($current_group as $resolution_info) {
// Get all the combinations for the next groups.
$next_points = $this->getPoints($grouped_by_token);
foreach ($next_points as $next_point) {
// Prepend the current resolution for each point.
$points[] = array_merge([$resolution_info], $next_point);
}
}
return $points;
}
/**
* Makes sure that the subject for replacement is a string.
*
* This is an abstraction to be able to treat 'uri' and 'body' replacements
* the same way.
*
* @param string $member_name
* Either 'body' or 'uri'.
* @param mixed $value
* The contents of the URI or the subrequest body.
*
* @returns string
* The serialized member.
*/
protected function serializeMember($member_name, $value) {
return $member_name === 'body'
// The body is an Object, to replace on it we serialize it first.
? Json::encode($value)
: $value;
}
/**
* Undoes the serialization that happened in _serializeMember.
*
* This is an abstraction to be able to treat 'uri' and 'body' replacements
* the same way.
*
* @param string $member_name
* Either 'body' or 'uri'.
* @param string $serialized
* The contents of the serialized URI or the serialized subrequest body.
*
* @returns mixed
* The unserialized member.
*/
protected function deserializeMember($member_name, $serialized) {
return $member_name === 'body'
// The body is an Object, to replace on it we serialize it first.
? Json::decode($serialized)
: $serialized;
}
/**
* Extracts the token replacements for a given subrequest.
*
* Given a subrequest there can be N tokens to be replaced. Each token can
* result in an list of values to be replaced. Each token may refer to many
* subjects, if the subrequest referenced in the token ended up spawning
* multiple responses. This function detects the tokens and finds the
* replacements for each token. Then returns a data structure that contains a
* list of replacements. Each item contains all the replacement needed to get
* a response for the initial request, given a particular subject for a
* particular JSONPath replacement.
*
* @param \Drupal\subrequests\Subrequest $subrequest
* The subrequest that contains the tokens.
* @param string $token_location
* Indicates if we are dealing with body or URI replacements.
* @param \Symfony\Component\HttpFoundation\Response[] $pool
* The collection of prior responses available for use with JSONPath.
*
* @returns array
* The structure containing a list of replacements for a subject response
* and a replacement candidate.
*/
protected function extractTokenReplacements(Subrequest $subrequest, $token_location, array $pool) {
// Turn the subject into a string.
$regexp_subject = $token_location === 'body'
? Json::encode($subrequest->body)
: $subrequest->uri;
// First find all the replacements to do. Use a regular expression to detect
// cases like "…{{req1.body@$.data.attributes.seasons..id}}…".
$found = $this->findTokens($regexp_subject);
// Make sure that duplicated tokens in the same location are treated as the
// same thing.
$found = array_values(array_reduce($found, function ($carry, $match) {
$carry[$match[0]] = $match;
return $carry;
}, []));
// Then calculate the replacements we will need to return.
$reducer = function ($token_replacements, $match) use ($pool) {
// Remove the .body part at the end since we only support the body
// replacement at this moment.
$provided_id = preg_replace('/\.body$/', '', $match[1]);
// Calculate what are the subjects to execute the JSONPath against.
$subjects = array_filter($pool, function (Response $response) use ($provided_id) {
// The response is considered a subject if it matches the content ID or
// it is a generated copy based of that content ID.
$pattern = sprintf('/%s(#.*)?/', preg_quote($provided_id));
$content_id = $this->getContentId($response);
return preg_match($pattern, $content_id);
});
if (count($subjects) === 0) {
$candidates = array_map(function ($response) {
$candidate = $this->getContentId($response);
return preg_replace('/#.*/', '', $candidate);
}, $pool);
throw new BadRequestHttpException(sprintf(
'Unable to find specified request for a replacement %s. Candidates are [%s].',
$provided_id,
implode(', ', $candidates)
));
}
// Find the replacements for this match given a subject. If there is more
// than one response object (a subject) for a given subrequest, then we
// generate one parallel subrequest per subject.
foreach ($subjects as $subject) {
$this->addReplacementsForSubject($match, $subject, $provided_id, $token_replacements);
}
return $token_replacements;
};
return array_reduce($found, $reducer, []);
}
/**
* Gets the clean Content ID for a response.
*
* Removes all the derived indicators and the surrounding angles.
*
* @param \Symfony\Component\HttpFoundation\Response $response
* The response to extract the Content ID from.
*
* @returns string
* The content ID.
*/
protected function getContentId(Response $response) {
$header = $response->headers->get('Content-ID', '');
return substr($header, 1, strlen($header) - 2);
}
/**
* Finds and parses all the tokens in a given string.
*
* @param string $subject
* The tokenized string. This is usually the URI or the serialized body.
*
* @returns array
* A list of all the matches. Each match contains the token, the subject to
* search replacements in and the JSONPath query to execute.
*/
protected function findTokens($subject) {
$matches = [];
$pattern = '/\{\{([^\{\}]+\.[^\{\}]+)@([^\{\}]+)\}\}/';
preg_match_all($pattern, $subject, $matches);
if (!$matches = array_filter($matches)) {
return [];
}
$output = [];
for ($index = 0; $index < count($matches[0]); $index++) {
// We only care about the first three items: full match, subject ID and
// JSONPath query.
$output[] = [
$matches[0][$index],
$matches[1][$index],
$matches[2][$index],
];
}
return $output;
}
/**
* Fill replacement values for a subrequest a subject and an structured token.
*
* @param array $match
* The structured replacement token.
* @param \Symfony\Component\HttpFoundation\Response $subject
* The response object the token refers to.
* @param string $provided_id
* The provided id.
* @param array $token_replacements
* The accumulated replacements. Adds items onto the array.
*/
protected function addReplacementsForSubject(array $match, Response $subject, $provided_id, array &$token_replacements) {
$json_object = new JsonObject($subject->getContent());
$to_replace = $json_object->get($match[2]) ?: [];
$token = $match[0];
// The replacements need to be strings. If not, then the replacement
// is not valid.
$this->validateJsonPathReplacements($to_replace);
$token_replacements[$provided_id] = empty($token_replacements[$provided_id])
? []
: $token_replacements[$provided_id];
$token_replacements[$provided_id][$token] = empty($token_replacements[$provided_id][$token])
? []
: $token_replacements[$provided_id][$token];
$token_replacements[$provided_id][$token] = array_merge($token_replacements[$provided_id][$token], $to_replace);
}
/**
* Validates tha the JSONPath query yields a string or an array of strings.
*
* @param array $to_replace
* The replacement candidates.
*
* @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
* When the replacements are not valid.
*/
protected function validateJsonPathReplacements($to_replace) {
$is_valid = is_array($to_replace)
&& array_reduce($to_replace, function ($valid, $replacement) {
return $valid && (is_string($replacement) || is_int($replacement) || is_bool($replacement) || is_float($replacement));
}, TRUE);
if (!$is_valid) {
throw new BadRequestHttpException(sprintf(
'The replacement token did find not a list of strings. Instead it found %s.',
Json::encode($to_replace)
));
}
}
}
@@ -0,0 +1,259 @@
<?php
namespace Drupal\subrequests\Normalizer;
use Drupal\Component\Serialization\Json;
use Drupal\Component\Uuid\Php;
use Drupal\subrequests\Subrequest;
use Drupal\subrequests\SubrequestsTree;
use JsonSchema\Constraints\Constraint;
use JsonSchema\Validator;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;
/**
* Denormalizer that builds the blueprint based on the incoming blueprint.
*/
class JsonBlueprintDenormalizer implements DenormalizerInterface, SerializerAwareInterface {
/**
* The serializer service.
*
* @var \Symfony\Component\Serializer\Serializer
*/
protected $serializer;
/**
* The Subrequests logger channel.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* The schema validator.
*
* This property will only be set if the validator library is available.
*
* @var \JsonSchema\Validator|null
*/
protected $validator;
/**
* {@inheritDoc}
*/
public function __construct(LoggerInterface $logger) {
$this->logger = $logger;
}
/**
* Sets the validator service if available.
*/
public function setValidator(Validator $validator = NULL) {
if ($validator) {
$this->validator = $validator;
}
elseif (class_exists(Validator::class)) {
$this->validator = new Validator();
}
}
/**
* {@inheritdoc}
*/
public function setSerializer(SerializerInterface $serializer): void {
if (!is_a($serializer, Serializer::class)) {
throw new \ErrorException('Serializer is unable to normalize or denormalize.');
}
$this->serializer = $serializer;
}
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = NULL, array $context = []): mixed {
$this->doValidateInput($data);
$data = array_map([$this, 'fillDefaults'], $data);
$subrequests = array_map(function ($item) {
return new Subrequest($item);
}, $data);
return $this->buildExecutionSequence($subrequests);
}
/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, $type, $format = NULL, array $context = []): bool {
return $format === 'json'
&& $type === SubrequestsTree::class
&& is_array($data)
&& !static::arrayIsKeyed($data);
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
SubrequestsTree::class => FALSE,
];
}
/**
* Check if an array is keyed.
*
* @param array $input
* The input array to check.
*
* @return bool
* True if the array is keyed.
*/
protected static function arrayIsKeyed(array $input) {
// Empty arrays are not keyed.
if (count($input) === 0) {
return FALSE;
}
$keys = array_keys($input);
// If the array does not start at 0, it is not numeric.
if ($keys[0] !== 0) {
return TRUE;
}
// If there is a non-numeric key, the array is not numeric.
$numeric_keys = array_filter($keys, 'is_numeric');
if (count($keys) != count($numeric_keys)) {
return TRUE;
}
// If the keys are not following the natural numbers sequence, then it is
// not numeric.
for ($index = 1; $index < count($keys); $index++) {
if ($keys[$index] - $keys[$index - 1] !== 1) {
return TRUE;
}
}
return FALSE;
}
/**
* Fill the defaults.
*
* @param array $raw_item
* The object to turn into a Subrequest input.
*
* @return array
* The complete Subrequest.
*/
protected function fillDefaults($raw_item) {
if (empty($raw_item['requestId'])) {
$uuid = new Php();
$raw_item['requestId'] = $uuid->generate();
}
if (!isset($raw_item['body'])) {
$raw_item['body'] = NULL;
}
elseif (!empty($raw_item['body'])) {
$raw_item['body'] = Json::decode($raw_item['body']);
}
$raw_item['headers'] = !empty($raw_item['headers']) ? $raw_item['headers'] : [];
$raw_item['waitFor'] = !empty($raw_item['waitFor']) ? $raw_item['waitFor'] : ['<ROOT>'];
$raw_item['_resolved'] = FALSE;
// Detect if there is an encoded token. If so, then decode the URI.
if (
!empty($raw_item['uri']) &&
strpos($raw_item['uri'], '%7B%7B') !== FALSE &&
strpos($raw_item['uri'], '%7D%7D') !== FALSE
) {
$raw_item['uri'] = urldecode($raw_item['uri']);
}
return $raw_item;
}
/**
* Wraps validation in an assert to prevent execution in production.
*
* @see self::validateInput
*/
public function doValidateInput($input) {
if (PHP_MAJOR_VERSION >= 8) {
assert($this->validateInput($input), 'A Subrequests blueprint failed validation (see the logs for details). Please report this in the issue queue on drupal.org');
}
}
/**
* Validates the consumers's blueprint against the subrequests payload format.
*
* @param mixed $input
* The blueprint sent by the consumer.
*
* @return bool
* FALSE if the input failed validation, otherwise TRUE.
*/
protected function validateInput($input) {
// If the validator isn't set, then the validation library is not installed.
if (!$this->validator) {
return TRUE;
}
$schema_path = dirname(dirname(__DIR__)) . '/schema.json';
$this->validator->validate($input, (object) ['$ref' => 'file://' . $schema_path], Constraint::CHECK_MODE_TYPE_CAST);
if (!$this->validator->isValid()) {
// Log any potential errors.
$this->logger->debug('Consumer\'s blueprint failed validation: @data', [
'@data' => Json::encode($input),
]);
$this->logger->debug('Validation errors: @errors', [
'@errors' => Json::encode($this->validator->getErrors()),
]);
}
return $this->validator->isValid();
}
/**
* Builds the execution sequence.
*
* Builds an array where each position contains the IDs of the requests to be
* executed. All the IDs in the same position in the sequence can be executed
* in parallel.
*
* @param \Drupal\subrequests\Subrequest[] $parsed
* The parsed requests.
*
* @return \Drupal\subrequests\SubrequestsTree
* The sequence of IDs grouped by execution order.
*/
public function buildExecutionSequence(array $parsed) {
$sequence = new SubrequestsTree();
$rooted_reqs = array_filter($parsed, function (Subrequest $item) {
return $item->waitFor === ['<ROOT>'];
});
$sequence->stack($rooted_reqs);
$subreqs_with_unresolved_deps = array_values(
array_filter($parsed, function (Subrequest $item) {
return $item->waitFor !== ['<ROOT>'];
})
);
$dependency_is_resolved = function (Subrequest $item) use ($sequence) {
return empty(array_diff($item->waitFor, $sequence->allIds()));
};
while (count($subreqs_with_unresolved_deps)) {
$no_deps = array_filter($subreqs_with_unresolved_deps, $dependency_is_resolved);
if (empty($no_deps)) {
throw new BadRequestHttpException('Waiting for unresolvable request. Abort.');
}
$sequence->stack($no_deps);
$subreqs_with_unresolved_deps = array_diff($subreqs_with_unresolved_deps, $no_deps);
}
return $sequence;
}
}
@@ -0,0 +1,153 @@
<?php
namespace Drupal\subrequests\Normalizer;
use Drupal\Component\Serialization\Json;
use Drupal\subrequests\Subrequest;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* Creates a request object for each Subrequest.
*/
class JsonSubrequestDenormalizer implements DenormalizerInterface {
/**
* Denormalizes data back into an object of the given class.
*
* @param mixed $data
* Data to restore.
* @param string $class
* The expected class to instantiate.
* @param string $format
* Format the given data was extracted from.
* @param array $context
* Options available to the denormalizer.
*
* @return object
* Return denormalized data as object.
*/
public function denormalize($data, $class, $format = NULL, array $context = []): mixed {
/** @var \Drupal\subrequests\Subrequest $data */
$path = parse_url($data->uri, PHP_URL_PATH);
$query = parse_url($data->uri, PHP_URL_QUERY) ?: [];
if (isset($query) && !is_array($query)) {
$_query = [];
parse_str($query, $_query);
$query = $_query;
}
/** @var \Symfony\Component\HttpFoundation\Request $master_request */
$master_request = $context['master_request'];
$request = Request::create(
$path,
static::getMethodFromAction($data->action),
empty($data->body) ? $query : (array) $data->body,
$master_request->cookies ? $master_request->cookies->all() : [],
$master_request->files ? $master_request->files->all() : [],
$master_request->server ? $master_request->server->all() : [],
empty($data->body) ? '' : Json::encode($data->body)
);
// Maintain the same session as in the master request.
$session = $master_request->getSession();
$request->setSession($session);
// Replace the headers by the ones in the subrequest.
foreach ($data->headers as $name => $value) {
$request->headers->set($name, $value);
}
$this::fixBasicAuth($request);
// Add the content ID to the sub-request.
$content_id = empty($data->requestId)
? md5(serialize($data))
: $data->requestId;
$request->headers->set('Content-ID', '<' . $content_id . '>');
return $request;
}
/**
* Checks whether the given class is supported for denormalization.
*
* @param mixed $data
* Data to denormalize from.
* @param string $type
* The class to which the data should be denormalized.
* @param string $format
* The format being deserialized from.
* @param array $context
* Options available to the denormalizer.
*
* @return bool
* Return whether the support denormalization.
*/
public function supportsDenormalization($data, $type, $format = NULL, array $context = []): bool {
return $type === Request::class
&& $data instanceof Subrequest;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
Request::class => FALSE,
Subrequest::class => FALSE,
];
}
/**
* Gets the HTTP method from the list of allowed actions.
*
* @param string $action
* The action name.
*
* @return string
* The HTTP method.
*/
public static function getMethodFromAction($action) {
switch ($action) {
case 'create':
return Request::METHOD_POST;
case 'update':
return Request::METHOD_PATCH;
case 'replace':
return Request::METHOD_PUT;
case 'delete':
return Request::METHOD_DELETE;
case 'exists':
return Request::METHOD_HEAD;
case 'discover':
return Request::METHOD_OPTIONS;
default:
return Request::METHOD_GET;
}
}
/**
* Adds the decoded username and password headers for Basic Auth.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request to fix.
*/
protected static function fixBasicAuth(Request $request) {
// The server will not set the PHP_AUTH_USER and PHP_AUTH_PW for the
// subrequests if needed.
if ($request->headers->has('Authorization')) {
$header = $request->headers->get('Authorization');
if (strpos($header, 'Basic ') === 0) {
[$user, $pass] = explode(':', base64_decode(substr($header, 6)));
$request->headers->set('PHP_AUTH_USER', $user);
$request->headers->set('PHP_AUTH_PW', $pass);
}
}
}
}
@@ -0,0 +1,68 @@
<?php
namespace Drupal\subrequests\Normalizer;
use Drupal\Component\Serialization\Json;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Normalizes multiple response objects into a single string.
*/
class MultiresponseJsonNormalizer implements NormalizerInterface {
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []): array|bool|string|int|float|null|\ArrayObject {
// Prepare the root content type header.
$headers = ['X-Sub-Content-Type' => $context['sub-content-type'], 'Content-Type' => 'application/json'];
// Join the content responses as a JSON object with the separator.
$output = array_reduce((array) $object, function ($carry, Response $part_response) {
$part_response->headers->set('Status', $part_response->getStatusCode());
$content_id = $part_response->headers->get('Content-ID');
$content_id = substr($content_id, 1, strlen($content_id) - 2);
$carry[$content_id] = [
'headers' => $part_response->headers->all(),
'body' => $part_response->getContent(),
];
return $carry;
}, []);
$content = Json::encode($output);
return [
'content' => $content,
'headers' => $headers,
];
}
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = NULL, array $context = []): bool {
if ($format !== 'json') {
return FALSE;
}
if (!is_array($data)) {
return FALSE;
}
$responses = array_filter($data, function ($response) {
return $response instanceof Response;
});
if (count($responses) === 0 || count($responses) !== count($data)) {
return FALSE;
}
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
'native-array' => FALSE,
Response::class => FALSE,
];
}
}
@@ -0,0 +1,73 @@
<?php
namespace Drupal\subrequests\Normalizer;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Normalizes multiple response objects into a single string.
*/
class MultiresponseNormalizer implements NormalizerInterface {
/**
* {@inheritdoc}
*/
public function normalize($object, $format = NULL, array $context = []): array|bool|string|int|float|null|\ArrayObject {
$delimiter = md5(microtime());
// Prepare the root content type header.
$content_type = sprintf(
'multipart/related; boundary="%s"; type=%s',
$delimiter,
$context['sub-content-type']
);
$headers = ['Content-Type' => $content_type];
$separator = sprintf("\r\n--%s\r\n", $delimiter);
// Join the content responses with the separator.
$content_items = array_map(function (Response $part_response) {
$part_response->headers->set('Status', $part_response->getStatusCode());
return sprintf(
"%s\r\n%s",
$part_response->headers,
$part_response->getContent()
);
}, (array) $object);
$content = sprintf("--%s\r\n", $delimiter) . implode($separator, $content_items) . sprintf("\r\n--%s--", $delimiter);
return [
'content' => $content,
'headers' => $headers,
];
}
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = NULL, $context = []): bool {
if ($format !== 'multipart-related') {
return FALSE;
}
if (!is_array($data)) {
return FALSE;
}
$responses = array_filter($data, function ($response) {
return $response instanceof Response;
});
if (count($responses) === 0 || count($responses) !== count($data)) {
return FALSE;
}
return TRUE;
}
/**
* {@inheritdoc}
*/
public function getSupportedTypes(?string $format): array {
return [
'native-array' => FALSE,
Response::class => FALSE,
];
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace Drupal\subrequests;
use Drupal\page_cache\StackMiddleware\PageCache as CorePageCache;
use Symfony\Component\HttpFoundation\Request;
/**
* Prevents the cache ID for a request from being statically cached.
*
* @todo Remove when https://www.drupal.org/i/3050383 is fixed.
*/
final class PageCache extends CorePageCache {
/**
* Static cache of cache IDs.
*
* @var \SplObjectStorage
*/
protected $cacheIds;
/**
* {@inheritdoc}
*/
protected function getCacheId(Request $request) {
if ($this->cacheIds === NULL) {
$this->cacheIds = new \SplObjectStorage();
}
if (!isset($this->cacheIds[$request])) {
$this->cacheIds[$request] = parent::getCacheId($request);
$this->cid = NULL;
}
return $this->cacheIds[$request];
}
}
@@ -0,0 +1,80 @@
<?php
namespace Drupal\subrequests;
/**
* Value object containing a Subrequest.
*/
class Subrequest {
/**
* The request ID.
*
* @var string
*/
public $requestId;
/**
* The parsed JSON.
*
* @var array
*/
public $body;
/**
* Array of key values.
*
* @var array
*/
public $headers;
/**
* The parent subrequests.
*
* @var string[]
*/
public $waitFor;
/**
* Is the subrequest resolved?
*
* @var bool
*/
// phpcs:ignore
public $_resolved;
/**
* The URI to request.
*
* @var string
*/
public $uri;
/**
* The action to perform.
*
* @var string
*/
public $action;
/**
* {@inheritDoc}
*/
public function __construct($values) {
$this->requestId = $values['requestId'];
$this->body = $values['body'];
$this->headers = $values['headers'];
$this->waitFor = $values['waitFor'];
$this->_resolved = $values['_resolved'];
$this->uri = $values['uri'];
$this->action = $values['action'];
}
/**
* Serialize the data.
*/
public function __toString() {
return serialize($this);
}
}
@@ -0,0 +1,96 @@
<?php
namespace Drupal\subrequests;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
/**
* Manages the subrequest data.
*/
class SubrequestsManager {
/**
* The kernel.
*
* @var \Symfony\Component\HttpKernel\HttpKernelInterface
*/
protected $httpKernel;
/**
* The serializer.
*
* @var \Symfony\Component\HttpKernel\HttpKernelInterface
*/
protected $serializer;
/**
* The path replacer.
*
* @var \Drupal\subrequests\JsonPathReplacer
*/
protected $replacer;
/**
* {@inheritDoc}
*/
public function __construct(HttpKernelInterface $http_kernel, DenormalizerInterface $serializer, JsonPathReplacer $replacer) {
$this->httpKernel = $http_kernel;
$this->serializer = $serializer;
$this->replacer = $replacer;
}
/**
* {@inheritDoc}
*/
public function request(SubrequestsTree $tree) {
// Loop through all sequential requests and merge them.
return $this->processBatchesSequence($tree);
}
/**
* Processes all the Subrequests until produce a collection of responses.
*
* @param \Drupal\subrequests\SubrequestsTree $tree
* The request tree that contains the requesting structure.
* @param int $_sequence
* (internal) The current index in the sequential chain.
* @param \Symfony\Component\HttpFoundation\Response[] $_responses
* (internal) The list of responses accumulated so far.
*
* @return \Symfony\Component\HttpFoundation\Response[]
* An array of responses when everything has been resolved.
*/
protected function processBatchesSequence($tree, $_sequence = 0, array $_responses = []) {
$batch = $tree[$_sequence];
// Perform all the necessary replacements for the elements in the batch.
$batch = $this->replacer->replaceBatch($batch, $_responses);
$results = array_map(function (Subrequest $subrequest) use ($tree) {
$master_request = $tree->getMasterRequest();
// Create a Symfony Request object based on the Subrequest.
/** @var \Symfony\Component\HttpFoundation\Request $request */
$request = $this->serializer->denormalize(
$subrequest,
Request::class,
NULL,
['master_request' => $master_request]
);
$response = $this->httpKernel
->handle($request, HttpKernelInterface::MAIN_REQUEST);
// Set the Content-ID header in the response.
$content_id = sprintf('<%s>', $subrequest->requestId);
$response->headers->set('Content-ID', $content_id);
return $response;
}, $batch);
// Accumulate the responses for the current batch.
$_responses = array_merge($_responses, $results);
// If we're not done, then call recursively with the updated arguments.
$_sequence++;
return $_sequence === $tree->count()
? $_responses
: $this->processBatchesSequence($tree, $_sequence, $_responses);
}
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\subrequests;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
/**
* Modifies container service definitions.
*
* @todo Remove when https://www.drupal.org/i/3050383 is fixed.
*/
final class SubrequestsServiceProvider extends ServiceProviderBase {
/**
* {@inheritdoc}
*/
public function alter(ContainerBuilder $container) {
parent::alter($container);
if (array_key_exists('page_cache', $container->getParameter('container.modules'))) {
$container->getDefinition('http_middleware.page_cache')
->setClass(PageCache::class);
}
}
}
@@ -0,0 +1,90 @@
<?php
namespace Drupal\subrequests;
use Symfony\Component\HttpFoundation\Request;
/**
* Value class that holds the execution tree.
*/
class SubrequestsTree extends \ArrayObject {
/**
* The master request.
*
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $masterRequest;
/**
* Adds a sequence of subrequests to the stack.
*
* @param \Drupal\subrequests\Subrequest[] $subrequests
* Subrequest data.
*/
public function stack($subrequests) {
// Make sure we only push Subrequest objects.
$this->append(array_filter($subrequests, function ($subrequest) {
return $subrequest instanceof Subrequest;
}));
}
/**
* Gets the number of levels in the stack.
*
* @return int
* Stack levels.
*/
public function getNumLevels() {
return $this->count();
}
/**
* Gets the lowest level.
*
* @return \Drupal\subrequests\Subrequest[]
* The subrequests in the level.
*/
public function getLowestLevel() {
return $this->offsetGet($this->count() - 1);
}
/**
* Gets the master request.
*
* @return \Symfony\Component\HttpFoundation\Request
* The request.
*/
public function getMasterRequest() {
return $this->masterRequest;
}
/**
* Sets the master request.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request.
*/
public function setMasterRequest(Request $request) {
$this->masterRequest = $request;
}
/**
* Gets all the subrequest IDs.
*
* @return \Drupal\subrequests\Subrequest[]
* All the subrequests in all levels.
*/
public function allIds() {
$subrequests = [];
foreach ($this as $item) {
$subrequests = array_merge($subrequests, array_values($item));
}
$all_request_ids = array_map(function (Subrequest $subrequest) {
return $subrequest->requestId;
}, $subrequests);
array_unshift($all_request_ids, '<ROOT>');
return array_unique($all_request_ids);
}
}
@@ -0,0 +1,12 @@
name: Subrequests
type: module
description: 'Add a front controller that you can use to make subrequests.'
core_version_requirement: ^10 || ^11
dependencies:
- drupal:serialization
package: Web services
# Information added by Drupal.org packaging script on 2024-08-06
version: '3.0.12'
project: 'subrequests'
datestamp: 1722952641
@@ -0,0 +1,3 @@
issue subrequests:
title: 'Issue subrequests'
description: 'Allow using the subrequests front controller to respond to multiple requests.'
@@ -0,0 +1,10 @@
subrequests.front-controller:
path: '/subrequests'
defaults:
_title: 'Returns bulk execution of multiple requests'
_controller: '\Drupal\subrequests\Controller\FrontController::handle'
methods: [GET, POST]
options:
_auth: ['basic_auth', 'cookie', 'oauth2', 'token_bearer']
requirements:
_permission: 'issue subrequests'
@@ -0,0 +1,31 @@
services:
subrequests.blueprint_manager:
class: Drupal\subrequests\Blueprint\BlueprintManager
arguments: ['@serializer']
logger.channel.subrequests:
parent: logger.channel_base
arguments: ['subrequests']
subrequests.json_path_replacer:
class: Drupal\subrequests\JsonPathReplacer
subrequests.subrequests_manager:
class: Drupal\subrequests\SubrequestsManager
arguments: ['@http_kernel', '@serializer', '@subrequests.json_path_replacer']
subrequests.denormalizer.blueprint.json:
class: Drupal\subrequests\Normalizer\JsonBlueprintDenormalizer
arguments: ['@logger.channel.subrequests']
tags:
- { name: normalizer, priority: 0 }
calls:
- [setValidator, []]
subrequests.denormalizer.subrequest.json:
class: Drupal\subrequests\Normalizer\JsonSubrequestDenormalizer
tags:
- { name: normalizer, priority: 0 }
subrequests.normalizer.multiresponse:
class: Drupal\subrequests\Normalizer\MultiresponseNormalizer
tags:
- { name: normalizer, priority: 0 }
subrequests.normalizer.multiresponse_json:
class: Drupal\subrequests\Normalizer\MultiresponseJsonNormalizer
tags:
- { name: normalizer, priority: 0 }
@@ -0,0 +1,33 @@
<?php
namespace Drupal\subrequests_test\Controller;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Controller\ControllerBase;
/**
* A controller returning simple responses for testing.
*/
class TestController extends ControllerBase {
/**
* Returns a JSON response that says "Alfa".
*
* @return \Drupal\Core\Cache\CacheableJsonResponse
* The response object.
*/
public function alpha(): CacheableJsonResponse {
return new CacheableJsonResponse('Alfa');
}
/**
* Returns a JSON response that says "Brava!".
*
* @return \Drupal\Core\Cache\CacheableJsonResponse
* The response object.
*/
public function bravo(): CacheableJsonResponse {
return new CacheableJsonResponse('Brava!');
}
}
@@ -0,0 +1,50 @@
<?php
namespace Drupal\subrequests_test;
use Drupal\Core\PageCache\RequestPolicyInterface;
use Drupal\Core\State\StateInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* A request policy that returns a specific pre-set value.
*/
class TestPolicy implements RequestPolicyInterface {
/**
* The state service.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
/**
* Constructs a TestPolicy object.
*
* @param \Drupal\Core\State\StateInterface $state
* State service.
*/
public function __construct(StateInterface $state) {
$this->state = $state;
}
/**
* Sets the value this policy will return.
*
* @param string|null $value
* The value this policy will return. Should be one of the ALLOW or DENY
* constants of \Drupal\Core\PageCache\RequestPolicyInterface, or NULL
* to have no opinion.
*/
public static function setValue(?string $value): void {
\Drupal::state()->set('subrequests_test_request_policy', $value);
}
/**
* {@inheritdoc}
*/
public function check(Request $request) {
return $this->state->get('subrequests_test_request_policy');
}
}
@@ -0,0 +1,11 @@
name: 'Subrequests Test'
type: module
package: Testing
description: Provides routes for functional tests of Subrequests.
dependencies:
- subrequests:subrequests
# Information added by Drupal.org packaging script on 2024-08-06
version: '3.0.12'
project: 'subrequests'
datestamp: 1722952641
@@ -0,0 +1,15 @@
subrequests_test.alpha:
path: '/subrequests-test/alpha'
defaults:
_controller: '\Drupal\subrequests_test\Controller\TestController::alpha'
requirements:
# Allowed for testing.
_access: 'TRUE'
subrequests_test.bravo:
path: '/subrequests-test/bravo'
defaults:
_controller: '\Drupal\subrequests_test\Controller\TestController::bravo'
requirements:
# Allowed for testing.
_access: 'TRUE'
@@ -0,0 +1,6 @@
services:
subrequests_test.request_policy:
class: Drupal\subrequests_test\TestPolicy
arguments: ['@state']
tags:
- { name: page_cache_request_policy }
+18
View File
@@ -0,0 +1,18 @@
<!--?xml version="1.0" encoding="UTF-8"?-->
<phpunit colors="true">
<testsuites>
<testsuite name="subrequests">
<directory>./src/</directory>
</testsuite>
</testsuites>
<!-- Filter for coverage reports. -->
<filter>
<blacklist>
<directory>./vendor</directory>
</blacklist>
<whitelist>
<directory>../src</directory>
</whitelist>
</filter>
</phpunit>
@@ -0,0 +1,110 @@
<?php
namespace Drupal\Tests\subrequests\Functional;
use Drupal\Core\Url;
use Drupal\subrequests_test\TestPolicy;
use Drupal\Tests\BrowserTestBase;
/**
* Tests subrequests with Page Cache enabled.
*
* @group subrequests
*/
class PageCacheTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'page_cache',
'subrequests_test',
'system',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests that subrequests work properly with Page Cache enabled.
*/
public function testPageCache(): void {
// Ensure page caching is always allowed in this test.
TestPolicy::setValue(TestPolicy::ALLOW);
$account = $this->drupalCreateUser(['issue subrequests']);
$this->drupalLogin($account);
// Warm the cache for the first sub-request.
$this->drupalGet('/subrequests-test/alpha');
$assert_session = $this->assertSession();
$assert_session->statusCodeEquals(200);
$assert_session->responseContains('Alfa');
// Ensure it was not (somehow) already cached.
$assert_session->responseHeaderEquals('X-Drupal-Cache', 'MISS');
$blueprint = [
[
'requestId' => 'alpha',
'uri' => Url::fromUserInput('/subrequests-test/alpha')->toString(),
'action' => 'view',
],
[
'requestId' => 'bravo',
'uri' => Url::fromUserInput('/subrequests-test/bravo')->toString(),
'action' => 'view',
],
];
$options = [
'query' => [
'query' => json_encode($blueprint, JSON_UNESCAPED_SLASHES),
],
];
$headers = [
'Content-Type' => 'application/json',
];
$this->drupalGet('/subrequests', $options, $headers);
$assert_session->statusCodeEquals(207);
// The request as a whole should be a cache miss.
$assert_session->responseHeaderEquals('X-Drupal-Cache', 'MISS');
// There should be two sub-responses.
$responses = $this->getResponses();
$this->assertCount(2, $responses);
// The first response should say Alfa and be a cache hit.
$this->assertStringContainsString('Alfa', $responses[0]);
$this->assertMatchesRegularExpression('/X-Drupal-Cache:\s+HIT/', $responses[0]);
// The second response should say Brava and be a cache miss.
$this->assertStringContainsString('Brava!', $responses[1]);
$this->assertMatchesRegularExpression('/X-Drupal-Cache:\s+MISS/', $responses[1]);
}
/**
* Returns the individual sub-responses from the most recent master request.
*
* @return string[]
* The responses from the most recent master request, in which the headers
* and body are separated by a single empty line.
*/
private function getResponses(): array {
$session = $this->getSession();
$matches = [];
preg_match('/boundary="([a-zA-Z0-9]+)"/', $session->getResponseHeader('Content-Type'), $matches);
$this->assertArrayHasKey(1, $matches);
$boundary = '--' . $matches[1];
$responses = explode($boundary, $session->getPage()->getContent());
// The first land last sub-responses are just empty strings because the
// response as a whole begins and ends with the boundary string.
$responses = array_slice($responses, 1, -1);
$responses = array_map('trim', $responses);
// Re-key the array before returning it.
return array_values($responses);
}
}
@@ -0,0 +1,76 @@
<?php
namespace Drupal\Tests\subrequests\Unit\Blueprint;
use Drupal\Core\Cache\CacheableResponse;
use Drupal\subrequests\Blueprint\BlueprintManager;
use Drupal\subrequests\Normalizer\JsonBlueprintDenormalizer;
use Drupal\subrequests\Normalizer\JsonSubrequestDenormalizer;
use Drupal\subrequests\Normalizer\MultiresponseJsonNormalizer;
use Drupal\subrequests\Normalizer\MultiresponseNormalizer;
use Drupal\subrequests\SubrequestsTree;
use Drupal\Tests\UnitTestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Encoder\JsonDecode;
use Symfony\Component\Serializer\Serializer;
/**
* @coversDefaultClass \Drupal\subrequests\Blueprint\BlueprintManager
* @group subrequests
*/
class BlueprintManagerTest extends UnitTestCase {
/**
* Blueprint manager.
*
* @var \Drupal\subrequests\Blueprint\BlueprintManager
*/
protected $sut;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$serializer = new Serializer(
[
new JsonBlueprintDenormalizer($this->createMock(LoggerInterface::class)),
new JsonSubrequestDenormalizer(),
new MultiresponseJsonNormalizer(),
new MultiresponseNormalizer(),
],
[new JsonDecode()]
);
$this->sut = new BlueprintManager($serializer);
}
/**
* Test for parse method.
*
* @covers ::parse
*/
public function testParse() {
$parsed = $this->sut->parse('[]', Request::create('foo'));
$this->assertInstanceOf(SubrequestsTree::class, $parsed);
$this->assertSame('/foo', $parsed->getMasterRequest()->getPathInfo());
}
/**
* Test for combineResponses method.
*
* @covers ::combineResponses
*/
public function testCombineResponses() {
$responses = [
new Response('foo', 200, ['lorem' => 'ipsum', 'Content-Type' => 'sparrow', 'head' => 'Ha!']),
new Response('Booh!', 201, ['dolor' => 'sid', 'Content-Type' => 'sparrow']),
];
$combined = $this->sut->combineResponses($responses, 'multipart-related');
$this->assertInstanceOf(CacheableResponse::class, $combined);
$this->assertStringContainsString('type=sparrow', $combined->headers->get('Content-Type'));
$this->assertStringContainsString('Booh!', $combined->getContent());
}
}
@@ -0,0 +1,161 @@
<?php
namespace Drupal\Tests\subrequests\Unit;
use Drupal\subrequests\JsonPathReplacer;
use Drupal\subrequests\Subrequest;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Response;
/**
* @coversDefaultClass \Drupal\subrequests\JsonPathReplacer
* @group subrequests
*/
class JsonPathReplacerTest extends UnitTestCase {
/**
* Json path replacer service.
*
* @var \Drupal\subrequests\JsonPathReplacer
*/
protected $sut;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->sut = new JsonPathReplacer();
}
/**
* Test for replaceBatch method.
*
* @covers ::replaceBatch
*/
public function testReplaceBatch() {
$batch = $responses = [];
$batch[] = new Subrequest([
'uri' => '/ipsum/{{foo.body@$.things[*]}}/{{bar.body@$.things[*]}}/{{foo.body@$.stuff}}',
'action' => 'sing',
'requestId' => 'oop',
'headers' => [],
'_resolved' => FALSE,
'body' => ['answer' => '{{foo.body@$.stuff}}'],
'waitFor' => ['foo'],
]);
$batch[] = new Subrequest([
'uri' => '/dolor/{{foo.body@$.stuff}}',
'action' => 'create',
'requestId' => 'oof',
'headers' => [],
'_resolved' => FALSE,
'body' => 'bar',
'waitFor' => ['foo'],
]);
$response = new Response('{"things":["what","keep","talking"],"stuff":42}');
$response->headers->set('Content-ID', '<foo>');
$responses[] = $response;
$response = new Response('{"things":["the","plane","is"],"stuff":"delayed"}');
$response->headers->set('Content-ID', '<bar>');
$responses[] = $response;
$actual = $this->sut->replaceBatch($batch, $responses);
$this->assertCount(10, $actual);
$paths = array_map(function (Subrequest $subrequest) {
return [$subrequest->uri, $subrequest->body];
}, $actual);
$expected_paths = [
['/ipsum/what/the/42', ['answer' => '42']],
['/ipsum/what/plane/42', ['answer' => '42']],
['/ipsum/what/is/42', ['answer' => '42']],
['/ipsum/keep/the/42', ['answer' => '42']],
['/ipsum/keep/plane/42', ['answer' => '42']],
['/ipsum/keep/is/42', ['answer' => '42']],
['/ipsum/talking/the/42', ['answer' => '42']],
['/ipsum/talking/plane/42', ['answer' => '42']],
['/ipsum/talking/is/42', ['answer' => '42']],
['/dolor/42', 'bar'],
];
$this->assertEquals($expected_paths, $paths);
$this->assertEquals(['answer' => 42], $actual[0]->body);
}
/**
* Test for replaceBatchSplit method.
*
* @covers ::replaceBatch
*/
public function testReplaceBatchSplit() {
$batch = $responses = [];
$batch[] = new Subrequest([
'uri' => 'test://{{foo.body@$.things[*].id}}/{{foo.body@$.things[*].id}}',
'action' => 'sing',
'requestId' => 'oop',
'headers' => [],
'_resolved' => FALSE,
'body' => ['answer' => '{{foo.body@$.stuff}}'],
'waitFor' => ['foo'],
]);
$response = new Response('{"things":[{"id":"what"},{"id":"keep"},{"id":"talking"}],"stuff":42}');
$response->headers->set('Content-ID', '<foo#0>');
$responses[] = $response;
$response = new Response('{"things":[{"id":"the"},{"id":"plane"}],"stuff":"delayed"}');
$response->headers->set('Content-ID', '<foo#1>');
$responses[] = $response;
$actual = $this->sut->replaceBatch($batch, $responses);
$this->assertCount(10, $actual);
$paths = array_map(function (Subrequest $subrequest) {
return [$subrequest->uri, $subrequest->body];
}, $actual);
$expected_paths = [
['test://what/what', ['answer' => '42']],
['test://what/what', ['answer' => 'delayed']],
['test://keep/keep', ['answer' => '42']],
['test://keep/keep', ['answer' => 'delayed']],
['test://talking/talking', ['answer' => '42']],
['test://talking/talking', ['answer' => 'delayed']],
['test://the/the', ['answer' => '42']],
['test://the/the', ['answer' => 'delayed']],
['test://plane/plane', ['answer' => '42']],
['test://plane/plane', ['answer' => 'delayed']],
];
$this->assertEquals($expected_paths, $paths);
}
/**
* Test for replaceBatchTypes method.
*
* @covers ::replaceBatch
*/
public function testReplaceBatchTypes() {
$batch = $responses = [];
$batch[] = new Subrequest([
'uri' => '/test/types',
'action' => 'create',
'requestId' => 'xyz',
'headers' => [],
'_resolved' => FALSE,
'body' => [
'You are number' => '{{foo.body@$.Number}}',
'Where am I' => '{{foo.body@$.Location}}',
'World of number two' => '{{foo.body@$.Two}}',
'Question' => 'Who is number {{foo.body@$.Who}}?',
'Michael' => '{{foo.body@$.Feigenbaum}}',
],
'waitFor' => ['foo'],
]);
$response = new Response('{"Number":6, "Location":"In the village", "Two":false, "Who":1, "Feigenbaum":4.6692}');
$response->headers->set('Content-ID', '<foo>');
$responses[] = $response;
$actual = $this->sut->replaceBatch($batch, $responses);
$this->assertIsInt($actual[0]->body['You are number']);
$this->assertIsString($actual[0]->body['Where am I']);
$this->assertIsBool($actual[0]->body['World of number two']);
$this->assertIsString($actual[0]->body['Question']);
$this->assertIsFloat($actual[0]->body['Michael']);
}
}
@@ -0,0 +1,104 @@
<?php
namespace Drupal\Tests\subrequests\Normalizer;
use Drupal\subrequests\Normalizer\JsonBlueprintDenormalizer;
use Drupal\subrequests\Subrequest;
use Drupal\subrequests\SubrequestsTree;
use Drupal\Tests\UnitTestCase;
use Prophecy\PhpUnit\ProphecyTrait;
use Psr\Log\LoggerInterface;
/**
* @coversDefaultClass \Drupal\subrequests\Normalizer\JsonBlueprintDenormalizer
* @group subrequests
*/
class JsonBlueprintDenormalizerTest extends UnitTestCase {
use ProphecyTrait;
/**
* Json blueprint denormalizer service.
*
* @var \Drupal\subrequests\Normalizer\JsonBlueprintDenormalizer
*/
protected $sut;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$logger = $this->prophesize(LoggerInterface::class);
$this->sut = new JsonBlueprintDenormalizer($logger->reveal());
}
/**
* Test for supportsDenormalization method.
*
* @dataProvider dataProviderSupportsNormalization
* @covers ::supportsDenormalization
*/
public function testSupportsDenormalization($data, $type, $format, $is_supported) {
$actual = $this->sut->supportsDenormalization($data, $type, $format);
$this->assertSame($is_supported, $actual);
}
/**
* Data provider for testSupportsDenormalization.
*/
public static function dataProviderSupportsNormalization(): array {
return [
[['a', 'b'], SubrequestsTree::class, 'json', TRUE],
['fail', SubrequestsTree::class, 'json', FALSE],
[['a', 'b'], SubrequestsTree::class, 'fail', FALSE],
[['fail' => 'a', 'b'], SubrequestsTree::class, 'json', FALSE],
];
}
/**
* Test for denormalize method.
*/
public function testDenormalize() {
$subrequests[] = [
'uri' => 'lorem',
'action' => 'view',
'requestId' => 'foo',
'body' => '"bar"',
'headers' => [],
];
$subrequests[] = [
'uri' => 'ipsum',
'action' => 'sing',
'requestId' => 'oop',
'body' => '[]',
'waitFor' => ['foo'],
];
$subrequests[] = [
// lorem?{{ipsum}}.
'uri' => 'lorem%3F%7B%7Bipsum%7D%7D',
'action' => 'create',
'requestId' => 'oof',
'body' => '"bar"',
'waitFor' => ['foo'],
];
$actual = $this->sut->denormalize($subrequests, SubrequestsTree::class, 'json', []);
$tree = new SubrequestsTree();
$tree->stack([new Subrequest(['waitFor' => ['<ROOT>'], '_resolved' => FALSE, 'body' => 'bar'] + $subrequests[0])]);
$tree->stack([
new Subrequest(['headers' => [], '_resolved' => FALSE, 'body' => []] + $subrequests[1]),
// Make sure the URL is decoded so we can perform apply regular
// expressions to it.
new Subrequest(
[
'headers' => [],
'_resolved' => FALSE,
'body' => 'bar',
'uri' => 'lorem?{{ipsum}}',
] + $subrequests[2]
),
]);
$this->assertEquals($tree, $actual);
}
}
@@ -0,0 +1,90 @@
<?php
namespace Drupal\Tests\subrequests\Normalizer;
use Drupal\Component\Serialization\Json;
use Drupal\subrequests\Normalizer\JsonSubrequestDenormalizer;
use Drupal\subrequests\Subrequest;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
/**
* @coversDefaultClass \Drupal\subrequests\Normalizer\JsonSubrequestDenormalizer
* @group subrequests
*/
class JsonSubrequestDenormalizerTest extends UnitTestCase {
/**
* Json subrequest denormalizer.
*
* @var \Drupal\subrequests\Normalizer\JsonSubrequestDenormalizer
*/
protected $sut;
/**
* {@inheritdoc}
*/
public function setUp(): void {
parent::setUp();
$this->sut = new JsonSubrequestDenormalizer();
}
/**
* Test for denormalize method.
*
* @covers ::denormalize
*/
public function testDenormalize() {
$class = Request::class;
$data = new Subrequest([
'requestId' => 'oof',
'body' => ['bar' => 'foo'],
'headers' => ['Authorization' => 'Basic ' . base64_encode('lorem:ipsum')],
'waitFor' => ['lorem'],
'_resolved' => FALSE,
'uri' => 'oop',
'action' => 'create',
]);
$request = Request::create('');
$request->setSession(new Session());
$actual = $this->sut->denormalize($data, $class, NULL, ['master_request' => $request]);
$this->assertSame('POST', $actual->getMethod());
$this->assertEquals(['bar' => 'foo'], Json::decode($actual->getContent()));
$this->assertSame('<oof>', $actual->headers->get('Content-ID'));
$this->assertSame('lorem', $actual->headers->get('PHP_AUTH_USER'));
$this->assertSame('ipsum', $actual->headers->get('PHP_AUTH_PW'));
}
/**
* Test for supportsDenormalization method.
*
* @dataProvider dataProviderSupportsNormalization
* @covers ::supportsDenormalization
*/
public function testSupportsDenormalization($data, $type, $format, $is_supported) {
$actual = $this->sut->supportsDenormalization($data, $type, $format);
$this->assertSame($is_supported, $actual);
}
/**
* Data provider for testSupportsDenormalization.
*/
public static function dataProviderSupportsNormalization(): array {
$subrequest = new Subrequest([
'requestId' => 'oof',
'body' => ['bar' => 'foo'],
'headers' => [],
'waitFor' => ['lorem'],
'_resolved' => FALSE,
'uri' => 'oop',
'action' => 'create',
]);
return [
[$subrequest, Request::class, NULL, TRUE],
['fail', Request::class, NULL, FALSE],
[$subrequest, 'fail', NULL, FALSE],
];
}
}
@@ -0,0 +1,80 @@
<?php
namespace Drupal\Tests\subrequests\Normalizer;
use Drupal\Component\Serialization\Json;
use Drupal\subrequests\Normalizer\MultiresponseJsonNormalizer;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Response;
/**
* @coversDefaultClass \Drupal\subrequests\Normalizer\MultiresponseJsonNormalizer
* @group subrequests
*/
class MultiresponseJsonNormalizerTest extends UnitTestCase {
/**
* Json multi response normalizer.
*
* @var \Drupal\subrequests\Normalizer\MultiresponseJsonNormalizer
*/
protected $sut;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->sut = new MultiresponseJsonNormalizer();
}
/**
* Test for supportsNormalization method.
*
* @dataProvider dataProviderSupportsNormalization
* @covers ::supportsNormalization
*/
public function testSupportsNormalization($data, $format, $is_supported) {
$actual = $this->sut->supportsNormalization($data, $format);
$this->assertSame($is_supported, $actual);
}
/**
* Data provider for testSupportsNormalization.
*/
public static function dataProviderSupportsNormalization(): array {
return [
[[new Response('')], 'json', TRUE],
[[], 'json', FALSE],
[[new Response('')], 'fail', FALSE],
[NULL, 'json', FALSE],
[[new Response(''), NULL], 'json', FALSE],
];
}
/**
* Test for normalize method.
*
* @covers ::normalize
*/
public function testNormalize() {
$sub_content_type = $this->getRandomGenerator()->string();
$data = [
new Response('Foo!', 200, ['Content-ID' => '<f>']),
new Response('Bar', 200, ['Content-ID' => '<b>']),
];
$actual = $this->sut->normalize($data, NULL, ['sub-content-type' => $sub_content_type]);
$this->assertSame(
'application/json',
$actual['headers']['Content-Type']
);
$this->assertSame(
$sub_content_type,
$actual['headers']['X-Sub-Content-Type']
);
$parsed = Json::decode($actual['content']);
$this->assertSame('Foo!', $parsed['f']['body']);
$this->assertSame('Bar', $parsed['b']['body']);
}
}
@@ -0,0 +1,72 @@
<?php
namespace Drupal\Tests\subrequests\Normalizer;
use Drupal\subrequests\Normalizer\MultiresponseNormalizer;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Response;
/**
* @coversDefaultClass \Drupal\subrequests\Normalizer\MultiresponseNormalizer
* @group subrequests
*/
class MultiresponseNormalizerTest extends UnitTestCase {
/**
* Multi response normalizer service.
*
* @var \Drupal\subrequests\Normalizer\MultiresponseNormalizer
*/
protected $sut;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->sut = new MultiresponseNormalizer();
}
/**
* Test for supportsNormalization method.
*
* @dataProvider dataProviderSupportsNormalization
* @covers ::supportsNormalization
*/
public function testSupportsNormalization($data, $format, $is_supported) {
$actual = $this->sut->supportsNormalization($data, $format);
$this->assertSame($is_supported, $actual);
}
/**
* Data provider for testSupportsNormalization.
*/
public static function dataProviderSupportsNormalization(): array {
return [
[[new Response('')], 'multipart-related', TRUE],
[[], 'multipart-related', FALSE],
[[new Response('')], 'fail', FALSE],
[NULL, 'multipart-related', FALSE],
[[new Response(''), NULL], 'multipart-related', FALSE],
];
}
/**
* Test for normalize method.
*
* @covers ::normalize
*/
public function testNormalize() {
$sub_content_type = $this->getRandomGenerator()->string();
$data = [new Response('Foo!'), new Response('Bar')];
$actual = $this->sut->normalize($data, NULL, ['sub-content-type' => $sub_content_type]);
$parts = explode('; ', $actual['headers']['Content-Type']);
parse_str($parts[1], $parts);
$delimiter = substr($parts['boundary'], 1, strlen($parts['boundary']) - 2);
$this->assertStringStartsWith('--' . $delimiter, $actual['content']);
$this->assertStringEndsWith('--' . $delimiter . '--', $actual['content']);
$this->assertMatchesRegularExpression("/\r\nFoo!\r\n/", $actual['content']);
$this->assertMatchesRegularExpression("/\r\nBar\r\n/", $actual['content']);
}
}
@@ -0,0 +1,106 @@
<?php
namespace Drupal\Tests\subrequests\Unit;
use Drupal\subrequests\JsonPathReplacer;
use Drupal\subrequests\Normalizer\JsonSubrequestDenormalizer;
use Drupal\subrequests\Subrequest;
use Drupal\subrequests\SubrequestsManager;
use Drupal\subrequests\SubrequestsTree;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Serializer\Encoder\JsonDecode;
use Symfony\Component\Serializer\Serializer;
/**
* @coversDefaultClass \Drupal\subrequests\SubrequestsManager
* @group subrequests
*/
class SubrequestsManagerTest extends UnitTestCase {
use ProphecyTrait;
/**
* Subrequest manager.
*
* @var \Drupal\subrequests\SubrequestsManager
*/
protected $sut;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$http_kernel = $this->prophesize(HttpKernelInterface::class);
$http_kernel
->handle(Argument::type(Request::class), HttpKernelInterface::MAIN_REQUEST)
->will(function ($args) {
return new Response($args[0]->getPathInfo());
});
$serializer = new Serializer(
[new JsonSubrequestDenormalizer()],
[new JsonDecode()]
);
$this->sut = new SubrequestsManager(
$http_kernel->reveal(),
$serializer,
new JsonPathReplacer()
);
}
/**
* Test for request method.
*
* @covers ::request
*/
public function testRequest() {
// Create and populate a tree.
$tree = new SubrequestsTree();
$subrequests[] = new Subrequest([
'uri' => 'lorem',
'action' => 'view',
'requestId' => 'foo',
'headers' => [],
'waitFor' => ['<ROOT>'],
'_resolved' => FALSE,
'body' => 'bar',
]);
$subrequests[] = new Subrequest([
'uri' => 'ipsum',
'action' => 'sing',
'requestId' => 'oop',
'headers' => [],
'_resolved' => FALSE,
'body' => [],
'waitFor' => ['foo'],
]);
$subrequests[] = new Subrequest([
'uri' => 'dolor',
'action' => 'create',
'requestId' => 'oof',
'headers' => [],
'_resolved' => FALSE,
'body' => 'bar',
'waitFor' => ['foo'],
]);
$tree->stack([$subrequests[0]]);
$tree->stack([$subrequests[1], $subrequests[2]]);
$master_request = new Request();
$master_request->setSession($this->createMock(SessionInterface::class));
$tree->setMasterRequest($master_request);
$actual = $this->sut->request($tree);
$this->assertSame('<foo>', $actual[0]->headers->get('Content-ID'));
$this->assertSame('<oop>', $actual[1]->headers->get('Content-ID'));
$this->assertSame('<oof>', $actual[2]->headers->get('Content-ID'));
$this->assertSame('/lorem', $actual[0]->getContent());
$this->assertSame('/ipsum', $actual[1]->getContent());
$this->assertSame('/dolor', $actual[2]->getContent());
}
}
@@ -0,0 +1,49 @@
<?php
namespace Drupal\Tests\subrequests\Unit;
use Drupal\subrequests\Subrequest;
use Drupal\subrequests\SubrequestsTree;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\subrequests\SubrequestsTree
* @group subrequests
*/
class SubrequestsTreeTest extends UnitTestCase {
/**
* Test for stack method.
*
* @dataProvider dataProviderStack
* @covers ::stack
* @covers ::getLowestLevel
* @covers ::getNumLevels
*/
public function testStack($input, $expected_count) {
$sut = new SubrequestsTree();
$sut->stack($input);
$this->assertSame(1, $sut->getNumLevels());
$this->assertCount($expected_count, $sut->getLowestLevel());
}
/**
* Data provider for testSupportsNormalization.
*/
public static function dataProviderStack(): array {
$defaults = [
'requestId' => 1,
'body' => '',
'headers' => [],
'waitFor' => [1],
'_resolved' => FALSE,
'uri' => '',
'action' => '',
];
return [
[[new Subrequest($defaults), 12, new Subrequest($defaults)], 2],
[[12], 0],
];
}
}