See #17 + #24, and all comments after that.

Comments

salmonek created an issue. See original summary.

salmonek’s picture

Issue summary: View changes
spleshka’s picture

Hi @salmonek, thanks for the report. I was able to reproduce the issue. It's quite interesting that the file is being created properly, but JSON API can't return it back to the client.

spleshka’s picture

I've debugged to the point where render context becomes not empty for private files. I'm not sure what is the reason of this behavior. For other file streams context behavior remains empty.

In the debugger I see this for the $context var:

*SplDoublyLinkedList*flags = 6
*SplDoublyLinkedList*dllist = array[1] 

For other file streams $context looks like this:

*SplDoublyLinkedList*flags = 6
*SplDoublyLinkedList*dllist = array[0]

It looks to me like it's some kind of var dump metadata in the variable which makes it non-empty.

wim leers’s picture

Something must be leaking cacheability metadata onto the global render context that \Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber creates specifically to detect those leaks.

What you want to do is put a breakpoint in \Drupal\Core\Render\RenderContext::bubble(). I'd bet that \Drupal\Core\StreamWrapper\PrivateStream::getExternalUrl() is causing cacheability metadata to bubble and hence leak onto the global render context.

(Many/most URLs are not generated in a hardcoded way — they're generated depending on the current request's hostname, base path, and so on. Which means they vary by those things, and hence bubble the associated cache contexts. I bet that that's happening here.)

wim leers’s picture

Issue tags: +D8 cacheability
spleshka’s picture

@Wim, you're absolutely right, it's \Drupal\Core\StreamWrapper\PrivateStream::getExternalUrl() bubbling the cacheability metadata. Is there a good way around this?

tom_ek’s picture

Hi, as far as I understand this - the problem lies in cache metadata for the POST request which should not be cached / should not contain the cacheability metadata. This is the core url generation issue and is being tackled here: https://www.drupal.org/node/2744715 . Applying the patch from this thread solved the issue for me.

grndlvl’s picture

This patch mentioned in #8 did not resolve the issue for me and still issued the same issue as before after applying the patch from #18 from #2744715: Generated URLs should only have cache contexts on GET/HEAD. I plan on looking into this more today.

grndlvl’s picture

Status: Active » Needs work
StatusFileSize
new15.33 KB

Ok... so I am not sure if this is the RIGHT fix here as I am not entirely sure how this is suppose to be fixed, however, based on what I understand from #2638686: Correctly handle cache data instead of throwing an Exception in EarlyRenderingControllerWrapperSubscriber() it appears closer to my issue in that I am using JSONAPI to add a new file and thus a POST, however, this check was still happening all because the Response implemented CacheableResponseInterface. So I took a page out of the rest module and creating different responses based on if the response should be cacheable.... I don't think I got them all, but I was able to get my particular instance to work this way.

@Wim Leers Additional guidance would certainly be appreciated here as this seems to be something you are well familiar with... it's a bit confusing to me as to what's actually happening here as from what I can tell all the code if functioning as intended, but something is wrong.

grndlvl’s picture

StatusFileSize
new887 bytes
new15.3 KB

Fixing error in patch for Error: Call to a member function isEmpty() on null in Drupal\jsonapi\EventSubscriber\ResourceResponseSubscriber->Drupal\jsonapi\EventSubscriber\{closure}() (line 131 of modules/contrib/jsonapi/src/EventSubscriber/ResourceResponseSubscriber.php).

jayelless’s picture

Thanks @grndlvl. The patch in #11 solved the problem for me.

Note that this patch need to be applied to module "jsonapi" rather than "jsonapi_file".

I think the name of the patch file could also be improved (refer https://www.drupal.org/patch/submit) to help with identification.

spleshka’s picture

Project: JSON API File » JSON:API

Changing the issue project, since the decision has to be made by JSONAPI's maintainers.

wim leers’s picture

Status: Needs work » Postponed (maintainer needs more info)
Issue tags: +Needs title update, +Needs issue summary update

"the decision" has to be made by JSON API's maintainers, you say, but the patch doesn't seem to have anything to do with the issue title or summary?

An updated issue title + summary would make it much easier to provide feedback :)

spleshka’s picture

Title: Can't upolad private file. » Enhance integration with JSON API File to allow provide file uploads
Issue summary: View changes
Issue tags: -Needs title update

Fair enough :) Fixed the title & updated the summary. I'm not entirely sure that the summary is completely correct given the lack of the involvement into the issue, so feel free to correct me (left the tag in place). So far it feels like the issue outside of JSON API File module and the potential work around (or a solid fix) should be implemented on JSON API level.

spleshka’s picture

Title: Enhance integration with JSON API File to allow provide file uploads » Enhance integration with JSON API File to allow private file uploads
wim leers’s picture

Title: Enhance integration with JSON API File to allow private file uploads » Port RequestHandler + ResourceResponse(Interface) improvements from REST module to JSON API
Status: Postponed (maintainer needs more info) » Needs work
Issue tags: +Needs tests
Related issues: +#2626298: REST module must cache only responses to GET requests

The issue title + summary claim this is about private file uploads. But there's zero mentions of that in the patch.

The patch appears to be porting #2626298: REST module must cache only responses to GET requests from REST module to JSON API module. I've been wanting to do something like that for a while now, but hadn't gotten to it yet.

Yes, I support the overall direction of this patch, but it has very little to do with file uploads at this point. We should still add an explicit test with the originally reported bug, to prevent regressions.


Review:

+++ b/src/ModifiedResourceResponse.php
@@ -0,0 +1,34 @@
+class ModifiedResourceResponse extends Response implements ResourceResponseInterface {

+++ b/src/ResourceResponse.php
@@ -15,19 +15,11 @@ use Symfony\Component\HttpFoundation\Response;
+class ResourceResponse extends Response implements CacheableResponseInterface, ResourceResponseInterface {

+++ b/src/ResourceResponseInterface.php
@@ -0,0 +1,18 @@
+interface ResourceResponseInterface {

Do we really want the exact same class names and even inheritance trees as the REST module's classes, but have alternative implementations?

And let's mark all of them @internal!

jayelless’s picture

The problem with creation of files in the "private://" file storage system appears to have disappeared with the jsonapi 8.x-1.7 release (noting that I went direct from 1.4 to 1.7).

e0ipso’s picture

I agree with the review in #17. Additionally:

  1. +++ b/src/Controller/EntityResource.php
    @@ -133,11 +135,31 @@ class EntityResource {
    +    $noncacheable_methods = array(
    +      Request::METHOD_POST,
    +      Request::METHOD_PUT,
    +      Request::METHOD_PATCH,
    +      Request::METHOD_DELETE,
    +    );
    

    Maybe use !$request->isMethodSafe() from the request object.

  2. +++ b/src/EventSubscriber/ResourceResponseSubscriber.php
    @@ -127,7 +128,11 @@ class ResourceResponseSubscriber implements EventSubscriberInterface {
    -          return $serializer->serialize($data, $format, ['request' => $request, 'cacheable_metadata' => $response->getCacheableMetadata()]);
    +          if ($response instanceof CacheableResponseInterface) {
    +            return $serializer->serialize($data, $format, ['request' => $request, 'cacheable_metadata' => $response->getCacheableMetadata()]);
    +          }
    +
    +          return $serializer->serialize($data, $format, ['request' => $request]);
    

    Let's make sure we always add the 'cacheable_metadata' to the context. Even if it's not a cacheable response. We may need to create a new NullCacheableMetadata object that follows the Null pattern.

e0ipso’s picture

The problem with creation of files in the "private://" file storage system appears to have disappeared with the jsonapi 8.x-1.7 release (noting that I went direct from 1.4 to 1.7).

@jlscott w00t! Can we reflect that in the issue summary?

jayelless’s picture

Unfortunately I appear to have been mistaken. The success I had must have been due to an anomaly on my development environment, as the issue is still present on the Acquia environments. What is more, the patch no longer applies to 1.7 :(. I guess it needs to be re-rolled.

jayelless’s picture

StatusFileSize
new14.35 KB

Rerolled patch file attached.

e0ipso’s picture

@jlscott any chance you can write the tests requested in #17? If so, we can find a way to implement the missing feedback in here one way or another :-)

Thanks for you contributions!

wim leers’s picture

Recently, more improvements landed in core's REST RequestHandler (#2853460: Simplify RequestHandler: make it no longer ContainerAware, split up ::handle() + #2935783: RequestHandler's handle method interacts with the Route object but should be able to just declare arguments). I'm going to port all of these over at once. Thanks to #2930028: Comprehensive JSON API integration test coverage phase 1: for every entity type, individual resources only + #2932031: Comprehensive JSON API integration test coverage phase 2: for every entity type, complex use-cases, we can now do this with a high level of certainty that we're not regressing!

The test coverage unveiled problems wrt cacheable responses, which #2933939: JSON API module must not send cacheable responses to PATCH, POST and DELETE requests fixed. So this:

Do we really want the exact same class names and even inheritance trees as the REST module's classes, but have alternative implementations?

which I raised in #17 and @e0ipso agreed with in #19 is no longer relevant, because we don't need to fix it here anymore: #2933939 implemented a simpler approach that is also more in line with what the JSON API module's architecture. (Where there's more levels of indirection, more reuse of objects, more value objects — because http://jsonapi.org/format is a much more capable format.)

wim leers’s picture

Assigned: Unassigned » wim leers

I'll take this on next week.

gabesullice’s picture

wim leers’s picture

Issue tags: +blocker

Now actively working on this, it's a blocker for some of the things @gabesullice is/was working on.

wim leers’s picture

Title: Port RequestHandler + ResourceResponse(Interface) improvements from REST module to JSON API » [PP-1] Port RequestHandler + ResourceResponse(Interface) improvements from REST module to JSON API
Status: Needs work » Postponed

This is blocked on #2940342: Cacheability metadata on an entity fields' properties is lost. Because without that issue being fixed, there's a definite risk that we regress in the handling of cacheability in this issue.

wim leers’s picture

Title: [PP-1] Port RequestHandler + ResourceResponse(Interface) improvements from REST module to JSON API » Port RequestHandler + ResourceResponse(Interface) improvements from REST module to JSON API
gabesullice’s picture

Status: Postponed » Needs work
wim leers’s picture

Thanks 😅

wim leers’s picture

I’ve really started working on this now. I’m increasingly convinced we should block this on:

  1. #2935370: Mark the JSON API serializer, normalizer and encoder services as private
  2. #2941685: Port parameter based resource config from REST module

(in that order), and then roll this on top of both of them. Because both of them make absolutely crucial simplifications.

wim leers’s picture

Title: Port RequestHandler + ResourceResponse(Interface) improvements from REST module to JSON API » [PP-3] Port RequestHandler + ResourceResponse(Interface) improvements from REST module to JSON API
Status: Needs work » Postponed
wim leers’s picture

To clarify #33:

  1. #29353750 causes all services to be injected rather than located
  2. #2941685 ports #2935783: RequestHandler's handle method interacts with the Route object but should be able to just declare arguments and #2853460: Simplify RequestHandler: make it no longer ContainerAware, split up ::handle(), which are two crucial recent improvements in core's REST module.
wim leers’s picture

StatusFileSize
new934 bytes
new63 KB

I've successfully rebased #2941685 on top of #2935370, see #2941685-15: Port parameter based resource config from REST module: tests are green. Time to get this going!


Let's start with something simple: remove \Drupal\jsonapi\Controller\RequestHandler::$requiredCacheContexts. That should no longer be necessary.

The "combined" patch includes #2935370-24: Mark the JSON API serializer, normalizer and encoder services as private + #2941685-15: Port parameter based resource config from REST module.

wim leers’s picture

StatusFileSize
new815 bytes
new1.69 KB
new63.77 KB

Excellent, only BlockTest failed, and this makes sense: its expectations just need to be updated. Now it matches core's \Drupal\Tests\rest\Functional\EntityResource\Block\BlockResourceTestBase::getExpectedCacheContexts()!

wim leers’s picture

StatusFileSize
new7.86 KB
new8.77 KB
new67.18 KB

This ports #2853460: Simplify RequestHandler: make it no longer ContainerAware, split up ::handle() as much as possible:

  1. It replaces JSON API's ::deserializeBody() with REST's more refined ::deserialize(). Doing that actually fixes #2943165: Failing to decode should result in a 400 response, failing to denormalize should result in a 422 response.
  2. We can't reuse \Drupal\jsonapi\Controller\RequestHandler::getNormalizedRequestMethod(), because unlike the REST module, JSON API supports multiple methods per route.
wim leers’s picture

  1. +++ b/src/Controller/RequestHandler.php
    @@ -109,13 +110,7 @@ class RequestHandler {
    +    $unserialized = $this->deserialize($request, $resource_type);
    
    @@ -153,35 +148,57 @@ class RequestHandler {
    -  public function deserializeBody(Request $request, ResourceType $resource_type) {
    +  protected function deserialize(Request $request, ResourceType $resource_type) {
    

    This is what #2853460: Simplify RequestHandler: make it no longer ContainerAware, split up ::handle() was all about! So, yay for seeing this ported!

  2. +++ b/src/Controller/RequestHandler.php
    @@ -153,35 +148,57 @@ class RequestHandler {
    +        $unserialized = $this->serializer->decode($received, 'api_json');
    ...
    +        throw new BadRequestHttpException($e->getMessage());
    ...
    +        $unserialized = $this->serializer->denormalize($unserialized, $request->get('serialization_class'), 'api_json', [
    

    Separate decoding and denormalizing is what fixes #2943165: Failing to decode should result in a 400 response, failing to denormalize should result in a 422 response.

  3. +++ b/tests/src/Functional/BlockTest.php
    @@ -137,6 +137,7 @@ class BlockTest extends ResourceTestBase {
    +    // @see ::createEntity()
    

    This should've been part of #37 😳

  4. +++ b/tests/src/Functional/ResourceTestBase.php
    @@ -897,8 +897,7 @@ abstract class ResourceTestBase extends BrowserTestBase {
    -    // @todo Uncomment in https://www.drupal.org/project/jsonapi/issues/2943165.
    -    /* $this->assertResourceErrorResponse(400, 'Bad Request', 'Syntax error', $response); */
    +    $this->assertResourceErrorResponse(400, 'Syntax error', $response);
    
    @@ -1169,8 +1168,7 @@ abstract class ResourceTestBase extends BrowserTestBase {
    -    // @todo Uncomment in https://www.drupal.org/project/jsonapi/issues/2943165.
    -    /* $this->assertResourceErrorResponse(400, 'Syntax error', $response); */
    +    $this->assertResourceErrorResponse(400, 'Syntax error', $response);
    

    This is what proves it fixed #2943165: Failing to decode should result in a 400 response, failing to denormalize should result in a 422 response.

wim leers’s picture

wim leers’s picture

StatusFileSize
new5.5 KB
new14.24 KB
new68.69 KB

Two fails.

  1. 1) Drupal\Tests\jsonapi\Unit\Controller\RequestHandlerTest::testDeserializeBodyFail
    Failed asserting that exception of type "Error" matches expected exception "\Symfony\Component\HttpKernel\Exception\HttpException".
    
    2) Drupal\Tests\jsonapi\Unit\Controller\RequestHandlerTest::testDeserializeBodyFail
    @covers method does not exist \Drupal\jsonapi\Controller\RequestHandler::deserializeBody: Drupal\Tests\jsonapi\Unit\Controller\RequestHandlerTest::testDeserializeBodyFail
    

    This is doing a pseudo unit test of RequestHandler::deserializeBody(). That method was renamed. But also, apparently it was public before. Now we know why: just for this test. Fortunately we now have integration test coverage actually catching this, so we can simply remove this test altogether!

  2. 1) Drupal\Tests\jsonapi\Functional\JsonApiFunctionalTest::testWrite
    Failed asserting that 400 matches expected 422.
    
    /var/www/html/core/tests/Drupal/Tests/BrowserTestBase.php:1286
    /var/www/html/modules/contrib/jsonapi/tests/src/Functional/JsonApiFunctionalTest.php:598
    

    Fixing #2943165: Failing to decode should result in a 400 response, failing to denormalize should result in a 422 response caused this to fail. Because we're now getting the expected 400 instead of 422. Expanded this test coverage.

wim leers’s picture

100% done now with porting #2853460: Simplify RequestHandler: make it no longer ContainerAware, split up ::handle(). Current diffstat:

5 files changed, 76 insertions, 124 deletions.

🎉

wim leers’s picture

StatusFileSize
new1.21 KB
new14.63 KB
new68.67 KB

Another issue that should definitely be ported is #2807501: ResourceResponse::$responseData is serialized, but is never used: unserializing it on every Page Cache hit is a huge performance penalty. Even though #2855693: Remove \Drupal\jsonapi\Controller\RequestHandler::renderJsonApiResponse(), add \Drupal\jsonapi\EventSubscriber\ResourceResponseSubscriber already ported this over a year ago, it did not yet remove all executeInRenderContext() calls: somehow JSON API ended up with multiple of those. No problem. Let's see what fails.

wim leers’s picture

StatusFileSize
new3.27 KB
new17.58 KB
new71.38 KB

This should fix some (hopefully most) of #43's failures.

wim leers’s picture

wim leers’s picture

Title: [PP-3] Port RequestHandler + ResourceResponse(Interface) improvements from REST module to JSON API » [PP-2] Port RequestHandler + ResourceResponse(Interface) improvements from REST module to JSON API
wim leers’s picture

Fixing all of #43's failure leads us too far out of scope. #44 already kind of shows this: the current LinkManager documentation is a lie: it pretends strings are returned and that's it, but it actually also bubbles cacheability metadata out-of-band. That's where all the failures are coming from.

The JSON API module is hardly to blame: it based this "link manager" idea off of core's \Drupal\hal\LinkManager\LinkManager … and that was similarly flawed until very recently: #2864816: HAL LinkManager doesn't add 'url.site' cache context when needed.

Created #2952714: Group module's GroupAccessResult::allowedIfHasGroupPermission(s)() does not include cacheability to fix that at some point in the future. So, reverting #43+#44's interdiffs, and instead adding two @todos pointing to that new issue.

wim leers’s picture

StatusFileSize
new4 KB
new18.46 KB
new60.48 KB

Per #24, we don't need the ResourceResponse(Interface) changes anymore, and #2626298: REST module must cache only responses to GET requests has been solved. What is necessary, is verifying that JSON API's ResourceResponseSubscriber resembles rest.module's as much as possible, to ensure minimum divergence and maximum carrying over of improvements/bugfixes.

Doing that comparison shows that they are already maximally identical. (Note that JSON API's ResourceResponseSubscriber was added in #2855693: Remove \Drupal\jsonapi\Controller\RequestHandler::renderJsonApiResponse(), add \Drupal\jsonapi\EventSubscriber\ResourceResponseSubscriber.)

Notes:

  1. Point 6 in the classdoc says
     *    It has a different priority, to ensure it runs before the Dynamic Page
     *    Cache event subscriber — but this should also be fixed in the original
     *    class, see issue
    

    This has since been fixed! So now this can be made consistent! Point removed :)

  2. #2933939: JSON API module must not send cacheable responses to PATCH, POST and DELETE requests modified the class, but didn't update the classdoc. Point documenting a difference added.
wim leers’s picture

Title: [PP-2] Port RequestHandler + ResourceResponse(Interface) improvements from REST module to JSON API » [PP-2] Port RequestHandler + ResourceResponseSubscriber improvements from REST module to JSON API
Assigned: wim leers » Unassigned
Issue summary: View changes
Issue tags: -Needs tests
wim leers’s picture

Assigned: Unassigned » wim leers
Priority: Major » Normal

Oh, almost forgot: I also inspected the git log for both REST's RequestHandler and ResourceResponseSubscriber, and did not find any other issues/commits that need to be ported to JSON API's classes with the same name.

wim leers’s picture

Assigned: wim leers » Unassigned
Priority: Normal » Major

d.o--

gabesullice’s picture

Status: Postponed » Needs work

This looks awesome. I have a couple suggestions that are independent of the prerequisites, so moving back to needs work.

  1. +++ b/src/Controller/RequestHandler.php
    @@ -133,21 +126,23 @@ class RequestHandler {
    -    $action = $this->action($request, $resource_type, $method);
    +    $action = $this->action($request, $resource_type);
    

    Understanding: The $request already carries the method information.

  2. +++ b/src/Controller/RequestHandler.php
    @@ -156,35 +151,57 @@ class RequestHandler {
    +   *   An object normalization, ikf there is a valid request body. NULL if there
    

    s/ikf/if/

  3. +++ b/src/Controller/RequestHandler.php
    @@ -156,35 +151,57 @@ class RequestHandler {
    -    if (empty($received) || $request->isMethodCacheable()) {
    

    Understanding: We can drop the isMethodCacheable because anything with a body (POST/PATCH) is not cacheable.

  4. +++ b/src/Controller/RequestHandler.php
    @@ -156,35 +151,57 @@ class RequestHandler {
    +      // These two serialization exception types mean there was a problem with
    +      // the structure of the decoded data and it's not valid.
    +      catch (UnexpectedValueException $e) {
    ...
    +      catch (InvalidArgumentException $e) {
    

    This is a nice DX improvement.

  5. +++ b/src/Controller/RequestHandler.php
    @@ -194,15 +211,13 @@ class RequestHandler {
    -  protected function action(Request $request, ResourceType $resource_type, $method) {
    +  protected function action(Request $request, ResourceType $resource_type) {
    ...
    +    switch (strtolower($request->getMethod())) {
    

    Clean!

  6. +++ b/src/EventSubscriber/ResourceResponseSubscriber.php
    @@ -122,8 +122,9 @@ class ResourceResponseSubscriber implements EventSubscriberInterface {
    +    $events[KernelEvents::RESPONSE][] = ['onResponse', 128];
    

    Why 128? That seems arbitrary and deserving of a comment.

gabesullice’s picture

Title: [PP-2] Port RequestHandler + ResourceResponseSubscriber improvements from REST module to JSON API » [PP-1] Port RequestHandler + ResourceResponseSubscriber improvements from REST module to JSON API
Related issues:
wim leers’s picture

Status: Needs work » Needs review
StatusFileSize
new1.36 KB
new18.56 KB
new60.59 KB
  1. Correct!
  2. ✔️
  3. Correct!
  4. :)
  5. :)
  6. Because this is identical to what \Drupal\rest\EventSubscriber\ResourceResponseSubscriber::getSubscribedEvents() does.
    It means we'll probably/hopefully be able to refactor rest and jsonapi's ResourceResponseSubscriber classes away, and move them to a shared one in serialization.

    Added a comment to clarify this.

gabesullice’s picture

Status: Needs review » Reviewed & tested by the community

💥

The last submitted patch, 11: 2883086-11.patch, failed testing. View results

The last submitted patch, 22: jsonapi-private-file-save-2883086-22.patch, failed testing. View results

chihada’s picture

I have the same problem in #2946746: Field data is unknown
I applied the patch 2883086-54-combined.patch but the problem did not solved
I am using Acquia Lightning 3.0.3 release

  • e0ipso committed da190cb on 8.x-1.x authored by Wim Leers
    Issue #2883086 by Wim Leers, grndlvl, jlscott, Spleshka, gabesullice,...
e0ipso’s picture

Status: Reviewed & tested by the community » Fixed

🎊❗️

Merged.

jayelless’s picture

Thanks everyone. I can confirm that release 1.15 has fixed the problems I had with saving files in the private file system.

  • e0ipso committed da190cb on 8.x-2.x authored by Wim Leers
    Issue #2883086 by Wim Leers, grndlvl, jlscott, Spleshka, gabesullice,...
wim leers’s picture

@jlscott: great! 🎉 Thanks for letting us know :)

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.