Bodies.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. /*
  2. * Copyright (c) 2022-2023, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Runtime/PromiseCapability.h>
  7. #include <LibWeb/Bindings/MainThreadVM.h>
  8. #include <LibWeb/Fetch/BodyInit.h>
  9. #include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
  10. #include <LibWeb/Fetch/Infrastructure/IncrementalReadLoopReadRequest.h>
  11. #include <LibWeb/Fetch/Infrastructure/Task.h>
  12. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  13. #include <LibWeb/Streams/AbstractOperations.h>
  14. #include <LibWeb/WebIDL/Promise.h>
  15. namespace Web::Fetch::Infrastructure {
  16. JS_DEFINE_ALLOCATOR(Body);
  17. JS::NonnullGCPtr<Body> Body::create(JS::VM& vm, JS::NonnullGCPtr<Streams::ReadableStream> stream)
  18. {
  19. return vm.heap().allocate_without_realm<Body>(stream);
  20. }
  21. JS::NonnullGCPtr<Body> Body::create(JS::VM& vm, JS::NonnullGCPtr<Streams::ReadableStream> stream, SourceType source, Optional<u64> length)
  22. {
  23. return vm.heap().allocate_without_realm<Body>(stream, source, length);
  24. }
  25. Body::Body(JS::NonnullGCPtr<Streams::ReadableStream> stream)
  26. : m_stream(move(stream))
  27. {
  28. }
  29. Body::Body(JS::NonnullGCPtr<Streams::ReadableStream> stream, SourceType source, Optional<u64> length)
  30. : m_stream(move(stream))
  31. , m_source(move(source))
  32. , m_length(move(length))
  33. {
  34. }
  35. void Body::visit_edges(Cell::Visitor& visitor)
  36. {
  37. Base::visit_edges(visitor);
  38. visitor.visit(m_stream);
  39. }
  40. // https://fetch.spec.whatwg.org/#concept-body-clone
  41. JS::NonnullGCPtr<Body> Body::clone(JS::Realm& realm)
  42. {
  43. HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
  44. // To clone a body body, run these steps:
  45. // 1. Let « out1, out2 » be the result of teeing body’s stream.
  46. auto [out1, out2] = m_stream->tee().release_value_but_fixme_should_propagate_errors();
  47. // 2. Set body’s stream to out1.
  48. m_stream = out1;
  49. // 3. Return a body whose stream is out2 and other members are copied from body.
  50. return Body::create(realm.vm(), *out2, m_source, m_length);
  51. }
  52. // https://fetch.spec.whatwg.org/#body-fully-read
  53. void Body::fully_read(JS::Realm& realm, Web::Fetch::Infrastructure::Body::ProcessBodyCallback process_body, Web::Fetch::Infrastructure::Body::ProcessBodyErrorCallback process_body_error, TaskDestination task_destination) const
  54. {
  55. // FIXME: 1. If taskDestination is null, then set taskDestination to the result of starting a new parallel queue.
  56. // FIXME: Handle 'parallel queue' task destination
  57. VERIFY(!task_destination.has<Empty>());
  58. auto task_destination_object = task_destination.get<JS::NonnullGCPtr<JS::Object>>();
  59. // 2. Let successSteps given a byte sequence bytes be to queue a fetch task to run processBody given bytes, with taskDestination.
  60. auto success_steps = [&realm, process_body, task_destination_object = task_destination_object](ReadonlyBytes bytes) -> ErrorOr<void> {
  61. // Make a copy of the bytes, as the source of the bytes may disappear between the time the task is queued and executed.
  62. auto bytes_copy = TRY(ByteBuffer::copy(bytes));
  63. queue_fetch_task(*task_destination_object, JS::create_heap_function(realm.heap(), [process_body, bytes_copy = move(bytes_copy)]() mutable {
  64. process_body->function()(move(bytes_copy));
  65. }));
  66. return {};
  67. };
  68. // 3. Let errorSteps optionally given an exception exception be to queue a fetch task to run processBodyError given exception, with taskDestination.
  69. auto error_steps = [&realm, process_body_error, task_destination_object](JS::GCPtr<WebIDL::DOMException> exception) {
  70. queue_fetch_task(*task_destination_object, JS::create_heap_function(realm.heap(), [process_body_error, exception]() {
  71. process_body_error->function()(exception);
  72. }));
  73. };
  74. // 4. Let reader be the result of getting a reader for body’s stream. If that threw an exception, then run errorSteps with that exception and return.
  75. // 5. Read all bytes from reader, given successSteps and errorSteps.
  76. // FIXME: Use streams for these steps.
  77. m_source.visit(
  78. [&](ByteBuffer const& byte_buffer) {
  79. if (auto result = success_steps(byte_buffer); result.is_error())
  80. error_steps(WebIDL::UnknownError::create(realm, "Out-of-memory"_string));
  81. },
  82. [&](JS::Handle<FileAPI::Blob> const& blob) {
  83. if (auto result = success_steps(blob->raw_bytes()); result.is_error())
  84. error_steps(WebIDL::UnknownError::create(realm, "Out-of-memory"_string));
  85. },
  86. [&](Empty) {
  87. error_steps(WebIDL::DOMException::create(realm, "DOMException"_fly_string, "Reading from Blob, FormData or null source is not yet implemented"_string));
  88. });
  89. }
  90. // https://fetch.spec.whatwg.org/#body-incrementally-read
  91. void Body::incrementally_read(ProcessBodyChunkCallback process_body_chunk, ProcessEndOfBodyCallback process_end_of_body, ProcessBodyErrorCallback process_body_error, TaskDestination task_destination)
  92. {
  93. HTML::TemporaryExecutionContext const execution_context { m_stream->realm(), HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
  94. VERIFY(task_destination.has<JS::NonnullGCPtr<JS::Object>>());
  95. // FIXME: 1. If taskDestination is null, then set taskDestination to the result of starting a new parallel queue.
  96. // FIXME: Handle 'parallel queue' task destination
  97. // 2. Let reader be the result of getting a reader for body’s stream.
  98. // NOTE: This operation will not throw an exception.
  99. auto reader = MUST(Streams::acquire_readable_stream_default_reader(m_stream));
  100. // 3. Perform the incrementally-read loop given reader, taskDestination, processBodyChunk, processEndOfBody, and processBodyError.
  101. incrementally_read_loop(reader, task_destination.get<JS::NonnullGCPtr<JS::Object>>(), process_body_chunk, process_end_of_body, process_body_error);
  102. }
  103. // https://fetch.spec.whatwg.org/#incrementally-read-loop
  104. void Body::incrementally_read_loop(Streams::ReadableStreamDefaultReader& reader, JS::NonnullGCPtr<JS::Object> task_destination, ProcessBodyChunkCallback process_body_chunk, ProcessEndOfBodyCallback process_end_of_body, ProcessBodyErrorCallback process_body_error)
  105. {
  106. auto& realm = reader.realm();
  107. // 1. Let readRequest be the following read request:
  108. auto read_request = realm.heap().allocate<IncrementalReadLoopReadRequest>(realm, *this, reader, task_destination, process_body_chunk, process_end_of_body, process_body_error);
  109. // 2. Read a chunk from reader given readRequest.
  110. reader.read_a_chunk(read_request);
  111. }
  112. // https://fetch.spec.whatwg.org/#byte-sequence-as-a-body
  113. WebIDL::ExceptionOr<JS::NonnullGCPtr<Body>> byte_sequence_as_body(JS::Realm& realm, ReadonlyBytes bytes)
  114. {
  115. // To get a byte sequence bytes as a body, return the body of the result of safely extracting bytes.
  116. auto [body, _] = TRY(safely_extract_body(realm, bytes));
  117. return body;
  118. }
  119. }