Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
220 changes: 87 additions & 133 deletions src/jsc/bindings/webcore/streams/BunAsyncIterableSource.cpp

Large diffs are not rendered by default.

309 changes: 119 additions & 190 deletions src/jsc/bindings/webcore/streams/BunStreamConsumers.cpp

Large diffs are not rendered by default.

407 changes: 141 additions & 266 deletions src/jsc/bindings/webcore/streams/BunStreamSource.cpp

Large diffs are not rendered by default.

202 changes: 101 additions & 101 deletions src/jsc/bindings/webcore/streams/JSCompressionStreamShared.cpp

Large diffs are not rendered by default.

121 changes: 48 additions & 73 deletions src/jsc/bindings/webcore/streams/JSDirectStreamController.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
#include <JavaScriptCore/SlotVisitorMacros.h>
#include <JavaScriptCore/SourceCode.h>
#include <JavaScriptCore/SubspaceInlines.h>
#include <JavaScriptCore/TopExceptionScope.h>
#include <wtf/Locker.h>
#include <wtf/text/StringBuilder.h>

Expand Down Expand Up @@ -428,86 +427,76 @@ static void closeDirectSinkForError(JSC::VM& vm, JSGlobalObject* globalObject, J
RELEASE_ASSERT_NOT_REACHED();
}

// The Bun-only `underlyingSource.close(reason)` lifecycle callback; the call is swallowed.
static void callUnderlyingSourceClose(JSC::VM& vm, JSGlobalObject* globalObject, JSDirectStreamController* controller, JSValue reason)
// The Bun-only `underlyingSource.close(reason)` lifecycle callback.
static void callUnderlyingSourceClose(JSC::VM& vm, JSGlobalObject* globalObject, JSObject* underlyingSource, JSValue reason)
{
auto scope = DECLARE_THROW_SCOPE(vm);
JSObject* underlyingSource = controller->m_underlyingSource.get();
if (!underlyingSource)
return;
JSValue closeFunction = underlyingSource->get(globalObject, builtinNames(vm).closePublicName());
RETURN_IF_EXCEPTION(scope, );
auto callData = JSC::getCallData(closeFunction);
if (callData.type == CallData::Type::None)
return;
auto catchScope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
MarkedArgumentBuffer args;
args.append(reason);
JSC::call(globalObject, closeFunction, callData, underlyingSource, args);
if (catchScope.exception()) [[unlikely]] {
if (takeAbruptCompletion(globalObject, catchScope).isEmpty())
return;
}
RELEASE_AND_RETURN(scope, );
}

// Errors the stream with `error`: rejects the pending read, errors the stream, tears the sink down,
// then runs the user's close(error) hook. The stream is fully errored before anything that can throw
// (the sink teardown, the hook) runs, so a throw from those propagates with the stream consistent.
void JSDirectStreamController::handleError(JSGlobalObject* globalObject, JSValue error)
{
auto& vm = getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);

const bool wasClosed = m_closed;
if (!wasClosed) {
auto catchScope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
closeDirectSinkForError(vm, globalObject, this, error);
if (catchScope.exception()) [[unlikely]] {
if (takeAbruptCompletion(globalObject, catchScope).isEmpty())
return;
}
}
m_closed = true;

// onClose() already ran the user's close() if the sink was closed (end() arming the
// final chunk leaves the stream Readable), so running it again would double it.
if (!wasClosed) {
callUnderlyingSourceClose(vm, globalObject, this, error);
RETURN_IF_EXCEPTION(scope, );
}
JSObject* underlyingSource = m_underlyingSource.get();
directStreamControllerClearSource(this);

if (auto* pendingRead = m_pendingRead.get()) {
m_pendingRead.clear();
rejectPromise(globalObject, pendingRead, error);
RETURN_IF_EXCEPTION(scope, );
}

auto* stream = m_stream.get();
if (stream && stream->m_state == ReadableStreamState::Readable)
RELEASE_AND_RETURN(scope, readableStreamError(globalObject, stream, error));
if (stream && stream->m_state == ReadableStreamState::Readable) {
readableStreamError(globalObject, stream, error);
RETURN_IF_EXCEPTION(scope, );
}

// onClose() already closed the sink and ran the user's close() if the controller was closed
// (end() arming the final chunk leaves the stream Readable), so doing it again would double it.
if (wasClosed)
return;
closeDirectSinkForError(vm, globalObject, this, error);
RETURN_IF_EXCEPTION(scope, );
RELEASE_AND_RETURN(scope, callUnderlyingSourceClose(vm, globalObject, underlyingSource, error));
}

// Invokes the user's pull() once, bracketed by m_pullInFlight (the spec sets [[pulling]]
// before invoking pullAlgorithm); left set only when a promise's settlement reaction will
// clear it. Returns the synchronous abrupt completion (empty on normal return/termination).
// clear it. This is the boundary into the user's pull(): as for the spec's promise-returning
// pullAlgorithm, its completion is converted here — a synchronous throw is returned as a value
// (the caller errors the stream with it and rejects the read), a returned promise's rejection goes
// to onDirectPullRejected. Empty on normal return, and on VM termination (left pending).
static JSValue callDirectPull(JSC::VM& vm, JSGlobalObject* globalObject, JSDirectStreamController* controller)
{
auto scope = DECLARE_THROW_SCOPE(vm);
StreamAsyncContextScope asyncContextScope(globalObject, controller->m_stream.get());
JSObject* pullFunction = controller->m_pull.get();
JSObject* underlyingSource = controller->m_underlyingSource.get();
controller->m_pullInFlight = true;
JSValue result;
JSValue abrupt;
{
auto catchScope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
MarkedArgumentBuffer args;
args.append(controller);
result = JSC::call(globalObject, pullFunction ? JSValue(pullFunction) : jsUndefined(), underlyingSource, args, "underlyingSource.pull is not a function"_s);
if (catchScope.exception()) [[unlikely]]
abrupt = takeAbruptCompletion(globalObject, catchScope);
}
if (!abrupt.isEmpty()) {
MarkedArgumentBuffer args;
args.append(controller);
JSValue result = JSC::call(globalObject, pullFunction ? JSValue(pullFunction) : jsUndefined(), underlyingSource, args, "underlyingSource.pull is not a function"_s);
if (JSC::Exception* exception = scope.exception()) [[unlikely]] {
controller->m_pullInFlight = false;
return abrupt;
TRY_CLEAR_EXCEPTION(scope, {});
return exception->value();
}
if (auto* pullPromise = dynamicDowncast<JSPromise>(result)) {
auto* runtime = JSStreamsRuntime::from(globalObject);
Expand Down Expand Up @@ -655,28 +644,25 @@ void JSDirectStreamController::onClose(JSGlobalObject* globalObject, JSValue rea
return;
// No "Closing" stream state exists: m_closed set here is what blocks re-entry.
m_closed = true;
JSObject* underlyingSource = m_underlyingSource.get();
directStreamControllerClearSource(this);

callUnderlyingSourceClose(vm, globalObject, this, reason);
JSValue flushed = endDirectSink(vm, globalObject, this);
RETURN_IF_EXCEPTION(scope, );
Comment thread
dylan-conway marked this conversation as resolved.
Resolved
directStreamControllerClearSource(this);
finishClose(globalObject, flushed);
RETURN_IF_EXCEPTION(scope, );
// The user's close(reason) hook runs once the stream is fully closed, so a throw from it
// propagates to whoever closed with nothing left half-done.
RELEASE_AND_RETURN(scope, callUnderlyingSourceClose(vm, globalObject, underlyingSource, reason));
}

JSValue flushed;
{
auto catchScope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
flushed = endDirectSink(vm, globalObject, this);
if (catchScope.exception()) [[unlikely]] {
JSValue thrown = takeAbruptCompletion(globalObject, catchScope);
if (!thrown)
return;
if (auto* pendingRead = m_pendingRead.get()) {
m_pendingRead.clear();
rejectPromise(globalObject, pendingRead, thrown);
return;
}
throwException(globalObject, scope, thrown);
return;
}
}
// The rest of close(): hand end()'s final chunk to whoever is reading (or arm it for the next read),
// then close the stream.
void JSDirectStreamController::finishClose(JSGlobalObject* globalObject, JSValue flushed)
{
auto& vm = getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
auto* stream = m_stream.get();

if (byteLengthOf(flushed)) {
if (auto* pendingRead = m_pendingRead.get()) {
Expand Down Expand Up @@ -853,28 +839,17 @@ JSC_DEFINE_HOST_FUNCTION(jsWebStreamsHandler_onDirectPullRejected, (JSGlobalObje
return JSValue::encode(jsUndefined());
}

// Runs from the end-of-tick queue with nothing above it (enterStreams): a throw from onFlush
// (e.g. a read request's chunkSteps) errors the stream.
JSC_DEFINE_HOST_FUNCTION(jsWebStreamsHandler_onDirectEndOfTickFlush, (JSGlobalObject * globalObject, CallFrame* callFrame))
{
auto& vm = getVM(globalObject);
auto* controller = dynamicDowncast<JSDirectStreamController>(callFrame->argument(1));
if (!controller) [[unlikely]]
return JSValue::encode(jsUndefined());
controller->m_endOfTickFlushArmed = false;
if (controller->m_closed || !controller->m_stream)
return JSValue::encode(jsUndefined());
// onFlush may throw (e.g. a read request's chunkSteps threw). This is a boundary:
// convert the abrupt completion into the direct controller's error action so the
// stream errors instead of surfacing as an uncaught nextTick exception. If erroring
// the stream itself throws, that is left for the tick runner to report.
auto scope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
controller->onFlush(globalObject);
if (scope.exception()) [[unlikely]] {
JSC::JSValue error = takeAbruptCompletion(globalObject, scope);
RETURN_IF_EXCEPTION(scope, {}); // termination is left pending
controller->handleError(globalObject, error);
RETURN_IF_EXCEPTION(scope, {});
}
return JSValue::encode(jsUndefined());
return enterStreams(globalObject, [&] { controller->onFlush(globalObject); }, [&](JSValue error) { controller->handleError(globalObject, error); });
}

// The FIVE public own methods are JSBoundFunctions over these [bound-convention] targets.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ class JSDirectStreamController final : public JSC::JSDestructibleObject {
void onFlush(JSC::JSGlobalObject*);
// handleDirectStreamError.
void handleError(JSC::JSGlobalObject*, JSC::JSValue error);
void finishClose(JSC::JSGlobalObject*, JSC::JSValue flushed);

private:
JSDirectStreamController(JSC::VM&, JSC::Structure*, Bun::WebStreams::DirectSinkKind);
Expand Down
88 changes: 17 additions & 71 deletions src/jsc/bindings/webcore/streams/JSReadableByteStreamController.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
#include <JavaScriptCore/ObjectConstructor.h>
#include <JavaScriptCore/SlotVisitorMacros.h>
#include <JavaScriptCore/SubspaceInlines.h>
#include <JavaScriptCore/TopExceptionScope.h>
#include <JavaScriptCore/TypedArrayType.h>
#include <algorithm>
#include <cstring>
Expand Down Expand Up @@ -91,28 +90,6 @@ static JSC::JSArrayBufferView* constructViewOfType(JSC::JSGlobalObject* globalOb
return nullptr;
}

// WebIDL "invoke a callback function" with a Promise<T> return type: an abrupt completion is
// converted into a rejected promise (a completion-record conversion), never a synchronous throw.
static JSC::JSPromise* invokePromiseReturningMethod(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSObject* method, JSC::JSValue thisValue, const JSC::MarkedArgumentBuffer& args)
{
auto scope = DECLARE_THROW_SCOPE(vm);
JSC::JSValue result;
JSC::JSValue thrown;
{
auto catchScope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
auto callData = JSC::getCallData(method);
ASSERT(callData.type != JSC::CallData::Type::None);
result = JSC::call(globalObject, method, callData, thisValue, args);
if (catchScope.exception()) [[unlikely]]
thrown = takeAbruptCompletion(globalObject, catchScope);
}
if (!thrown.isEmpty())
RELEASE_AND_RETURN(scope, promiseRejectedWith(globalObject, thrown));
if (result.isEmpty())
return nullptr;
RELEASE_AND_RETURN(scope, promiseResolvedWith(globalObject, result));
}

// The [[pullAlgorithm]] dispatch. The reachable kind set on a byte controller is exactly
// {JavaScript, Nothing, ByteTeeBranch}; the switch is total over SourceKind.
// Returns nullptr with no exception pending when the pull completed synchronously with a
Expand All @@ -132,25 +109,7 @@ static JSC::JSPromise* performByteControllerPullAlgorithm(JSC::VM& vm, JSC::JSGl
return nullptr;
}
StreamAsyncContextScope asyncContextScope(globalObject, controller->m_stream.get());
JSC::JSValue result;
JSC::JSValue thrown;
{
auto catchScope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
auto callData = JSC::getCallData(pullMethod);
ASSERT(callData.type != JSC::CallData::Type::None);
result = JSC::call(globalObject, pullMethod, callData, controller->m_algorithms.underlyingObject.get(), args);
if (catchScope.exception()) [[unlikely]]
thrown = takeAbruptCompletion(globalObject, catchScope);
}
if (!thrown.isEmpty()) [[unlikely]]
RELEASE_AND_RETURN(scope, promiseRejectedWith(globalObject, thrown));
if (result.isEmpty()) [[unlikely]]
return nullptr;
if (!result.isObject()) [[likely]]
return nullptr;
if (auto* resultPromise = dynamicDowncast<JSC::JSPromise>(result); resultPromise && resultPromise->isThenFastAndNonObservable())
return resultPromise;
RELEASE_AND_RETURN(scope, promiseResolvedWith(globalObject, result));
RELEASE_AND_RETURN(scope, invokeCallbackReturningPromiseFast(globalObject, pullMethod, controller->m_algorithms.underlyingObject.get(), args));
}
case SourceKind::Nothing:
return nullptr;
Expand Down Expand Up @@ -184,7 +143,7 @@ static JSC::JSPromise* performByteControllerCancelAlgorithm(JSC::VM& vm, JSC::JS
return nullptr;
}
StreamAsyncContextScope asyncContextScope(globalObject, controller->m_stream.get());
RELEASE_AND_RETURN(scope, invokePromiseReturningMethod(vm, globalObject, cancelMethod, controller->m_algorithms.underlyingObject.get(), args));
RELEASE_AND_RETURN(scope, invokeCallbackReturningPromise(globalObject, cancelMethod, controller->m_algorithms.underlyingObject.get(), args));
}
case SourceKind::Nothing:
RELEASE_AND_RETURN(scope, promiseFulfilledWith(globalObject, JSC::jsUndefined()));
Expand Down Expand Up @@ -817,21 +776,15 @@ void readableByteStreamControllerEnqueueClonedChunkToQueue(JSGlobalObject* globa
{
auto& vm = getVM(globalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
RefPtr<JSC::ArrayBuffer> cloneResult;
{
// CloneArrayBuffer is interpreted as a completion record: an abrupt completion errors
// the controller and is then rethrown.
auto catchScope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
cloneResult = cloneArrayBuffer(vm, globalObject, buffer, byteOffset, byteLength);
if (catchScope.exception()) [[unlikely]] {
JSValue thrown = takeAbruptCompletion(globalObject, catchScope);
if (thrown.isEmpty()) [[unlikely]]
return;
readableByteStreamControllerError(globalObject, controller, thrown);
RETURN_IF_EXCEPTION(scope, void());
throwException(globalObject, scope, thrown);
return;
}
RefPtr<JSC::ArrayBuffer> cloneResult = cloneArrayBuffer(vm, globalObject, buffer, byteOffset, byteLength);
if (JSC::Exception* exception = scope.exception()) [[unlikely]] {
// Spec step 2: "If cloneResult is an abrupt completion, perform
// ! ReadableByteStreamControllerError(controller, cloneResult.[[Value]]) and return cloneResult."
TRY_CLEAR_EXCEPTION(scope, );
readableByteStreamControllerError(globalObject, controller, exception->value());
RETURN_IF_EXCEPTION(scope, );
throwException(globalObject, scope, exception);
return;
}
readableByteStreamControllerEnqueueChunkToQueue(controller, WTF::move(cloneResult), 0, byteLength);
}
Expand Down Expand Up @@ -1042,20 +995,13 @@ void readableByteStreamControllerPullInto(JSGlobalObject* globalObject, JSReadab
size_t byteOffset = view->byteOffset();
size_t byteLength = view->byteLength();
RefPtr<JSC::ArrayBuffer> viewedBuffer = view->possiblySharedBuffer();
RefPtr<JSC::ArrayBuffer> buffer;
JSValue transferAbruptCompletion;
{
// "If bufferResult is an abrupt completion", route it to the read-into request's error steps.
auto catchScope = DECLARE_TOP_EXCEPTION_SCOPE(vm);
buffer = transferArrayBufferImpl(globalObject, *viewedBuffer);
if (catchScope.exception()) [[unlikely]] {
transferAbruptCompletion = takeAbruptCompletion(globalObject, catchScope);
if (transferAbruptCompletion.isEmpty()) [[unlikely]]
return;
}
RefPtr<JSC::ArrayBuffer> buffer = transferArrayBufferImpl(globalObject, *viewedBuffer);
if (JSC::Exception* exception = scope.exception()) [[unlikely]] {
// Spec step 10: "If bufferResult is an abrupt completion, perform readIntoRequest's error
// steps given bufferResult.[[Value]] and return."
TRY_CLEAR_EXCEPTION(scope, );
RELEASE_AND_RETURN(scope, readIntoRequest->errorSteps(globalObject, exception->value()));
}
if (!transferAbruptCompletion.isEmpty()) [[unlikely]]
RELEASE_AND_RETURN(scope, readIntoRequest->errorSteps(globalObject, transferAbruptCompletion));
auto* zigGlobalObject = defaultGlobalObject(globalObject);
JSPullIntoDescriptor* pullIntoDescriptor = JSPullIntoDescriptor::create(vm, JSStreamsRuntime::from(globalObject)->pullIntoDescriptorStructure(zigGlobalObject));
pullIntoDescriptor->m_bufferByteLength = buffer->byteLength();
Expand Down
Loading