@@ -52,12 +52,119 @@ namespace Babylon::Polyfills::Internal
5252 }
5353 };
5454
55- struct Blob ::StreamState
55+ class Blob ::StreamSource final : public Napi::ObjectWrap<Blob::StreamSource>
5656 {
57- std::shared_ptr<const Storage> BlobData;
58- size_t Position{};
59- size_t SegmentIndex{};
60- size_t SegmentOffset{};
57+ public:
58+ static Napi::Function Define (Napi::Env env)
59+ {
60+ return DefineClass (
61+ env,
62+ " BlobStreamSource" ,
63+ {
64+ InstanceMethod (" pull" , &StreamSource::Pull),
65+ InstanceMethod (" cancel" , &StreamSource::Cancel),
66+ });
67+ }
68+
69+ explicit StreamSource (const Napi::CallbackInfo& info)
70+ : Napi::ObjectWrap<StreamSource>{info}
71+ {
72+ if (info.Length () != 1 || !info[0 ].IsObject ())
73+ {
74+ throw Napi::TypeError::New (info.Env (), " Blob stream source requires a Blob." );
75+ }
76+
77+ const auto blob = Napi::ObjectWrap<Blob>::Unwrap (info[0 ].As <Napi::Object>());
78+ if (blob == nullptr )
79+ {
80+ throw Napi::TypeError::New (info.Env (), " Blob stream source requires a Blob." );
81+ }
82+ m_blobData = blob->m_data ;
83+ }
84+
85+ private:
86+ Napi::Value Pull (const Napi::CallbackInfo& info)
87+ {
88+ auto env = info.Env ();
89+ auto controller = info[0 ].As <Napi::Object>();
90+ if (!m_blobData || m_position >= m_blobData->Size )
91+ {
92+ controller.Get (" close" ).As <Napi::Function>().Call (controller, {});
93+ m_blobData.reset ();
94+ return env.Undefined ();
95+ }
96+
97+ constexpr size_t CHUNK_SIZE = 64 * 1024 ;
98+ const auto copyInto = [this ](std::byte* destination, size_t outputLength) {
99+ auto segmentIndex = m_segmentIndex;
100+ auto segmentOffset = m_segmentOffset;
101+ size_t remaining = outputLength;
102+
103+ while (remaining > 0 )
104+ {
105+ const auto & segment = m_blobData->Segments [segmentIndex];
106+ const auto copyLength = std::min (segment.Length - segmentOffset, remaining);
107+ std::memcpy (destination, segment.Bytes ->data () + segment.Offset + segmentOffset, copyLength);
108+ destination += copyLength;
109+ remaining -= copyLength;
110+ segmentOffset += copyLength;
111+ if (segmentOffset == segment.Length )
112+ {
113+ ++segmentIndex;
114+ segmentOffset = 0 ;
115+ }
116+ }
117+
118+ m_position += outputLength;
119+ m_segmentIndex = segmentIndex;
120+ m_segmentOffset = segmentOffset;
121+ };
122+
123+ const auto byobRequestValue = controller.Get (" byobRequest" );
124+ if (!byobRequestValue.IsUndefined () && !byobRequestValue.IsNull ())
125+ {
126+ const auto byobRequest = byobRequestValue.As <Napi::Object>();
127+ const auto viewValue = byobRequest.Get (" view" );
128+ if (!viewValue.IsTypedArray ())
129+ {
130+ throw Napi::TypeError::New (env, " Blob.stream() received an invalid BYOB request view." );
131+ }
132+
133+ const auto view = viewValue.As <Napi::TypedArray>();
134+ const auto outputLength = std::min ({CHUNK_SIZE , view.ByteLength (), m_blobData->Size - m_position});
135+ const auto outputBuffer = view.ArrayBuffer ();
136+ auto destination = static_cast <std::byte*>(outputBuffer.Data ()) + view.ByteOffset ();
137+ copyInto (destination, outputLength);
138+ byobRequest.Get (" respond" ).As <Napi::Function>().Call (byobRequest, {Napi::Number::New (env, outputLength)});
139+ }
140+ else
141+ {
142+ const auto outputLength = std::min (CHUNK_SIZE , m_blobData->Size - m_position);
143+ auto outputBuffer = Napi::ArrayBuffer::New (env, outputLength);
144+ copyInto (static_cast <std::byte*>(outputBuffer.Data ()), outputLength);
145+ auto output = Napi::Uint8Array::New (env, outputLength, outputBuffer, 0 );
146+ controller.Get (" enqueue" ).As <Napi::Function>().Call (controller, {output});
147+ }
148+
149+ if (m_position == m_blobData->Size )
150+ {
151+ controller.Get (" close" ).As <Napi::Function>().Call (controller, {});
152+ m_blobData.reset ();
153+ }
154+
155+ return env.Undefined ();
156+ }
157+
158+ Napi::Value Cancel (const Napi::CallbackInfo& info)
159+ {
160+ m_blobData.reset ();
161+ return info.Env ().Undefined ();
162+ }
163+
164+ std::shared_ptr<const Storage> m_blobData;
165+ size_t m_position{};
166+ size_t m_segmentIndex{};
167+ size_t m_segmentOffset{};
61168 };
62169
63170 void Blob::Initialize (Napi::Env env)
@@ -82,6 +189,17 @@ namespace Babylon::Polyfills::Internal
82189 descriptor.Set (" configurable" , true );
83190 descriptor.Set (" value" , JS_BLOB_CONSTRUCTOR_NAME );
84191 env.Global ().Get (" Object" ).As <Napi::Object>().Get (" defineProperty" ).As <Napi::Function>().Call (env.Global ().Get (" Object" ), {func.Get (" prototype" ), Napi::Symbol::WellKnown (env, " toStringTag" ), descriptor});
192+
193+ // Underlying stream sources are native ObjectWrap instances so
194+ // pull/cancel live on one shared prototype. Creating two native
195+ // functions for every Blob.stream() caused avoidable JSC Function
196+ // structure transitions and exposed a WebKitGTK LeakSanitizer
197+ // allocation during Worker teardown.
198+ auto sourceDescriptor = Napi::Object::New (env);
199+ sourceDescriptor.Set (" value" , StreamSource::Define (env));
200+ env.Global ().Get (" Object" ).As <Napi::Object>().Get (" defineProperty" ).As <Napi::Function>().Call (
201+ env.Global ().Get (" Object" ),
202+ {func, Napi::String::New (env, " __jsRuntimeHostBlobStreamSource" ), sourceDescriptor});
85203 env.Global ().Set (JS_BLOB_CONSTRUCTOR_NAME , func);
86204 }
87205 }
@@ -294,114 +412,14 @@ namespace Babylon::Polyfills::Internal
294412 throw Napi::TypeError::New (env, " Blob.stream() requires ReadableStream to be installed." );
295413 }
296414
297- auto source = Napi::Object::New (env);
298- auto stateOwner = Napi::External<StreamState>::New (
299- env,
300- new StreamState{m_data},
301- [](Napi::Env, StreamState* state) {
302- delete state;
303- });
304- auto state = stateOwner.Data ();
305-
306- // ReadableStream retains its underlying source as the receiver for the
307- // pull/cancel algorithms, so let that object own the callback state.
308- // The compile-time callback overload passes the state directly through
309- // napi_create_function. In contrast, a capturing Function::New allocates
310- // node-addon-api CallbackData and attaches it as a hidden property to
311- // every function. Besides two avoidable allocations per Blob stream,
312- // that path creates extra JSC Function structure transitions and exposed
313- // a system-WebKitGTK LeakSanitizer allocation during Worker teardown.
314- // Keep the owner on the internal source object with a string key.
315- // The legacy JSC Node-API adapter stringifies property keys in
316- // napi_set_property, so passing a Symbol here throws even though
317- // modern engines accept it.
318- source.Set (" __jsRuntimeHostBlobStreamState" , stateOwner);
415+ const auto blobConstructor = env.Global ().Get (" Blob" ).As <Napi::Object>();
416+ const auto sourceConstructor = blobConstructor.Get (" __jsRuntimeHostBlobStreamSource" ).As <Napi::Function>();
417+ auto source = sourceConstructor.New ({info.This ()});
319418 source.Set (" type" , " bytes" );
320- source.Set (" pull" , Napi::Function::New<&Blob::PullStream>(env, " pull" , state));
321- source.Set (" cancel" , Napi::Function::New<&Blob::CancelStream>(env, " cancel" , state));
322419
323420 return readableStreamValue.As <Napi::Function>().New ({source});
324421 }
325422
326- Napi::Value Blob::PullStream (const Napi::CallbackInfo& info)
327- {
328- auto env = info.Env ();
329- auto state = static_cast <StreamState*>(info.Data ());
330- auto controller = info[0 ].As <Napi::Object>();
331- if (!state->BlobData || state->Position >= state->BlobData ->Size )
332- {
333- controller.Get (" close" ).As <Napi::Function>().Call (controller, {});
334- state->BlobData .reset ();
335- return env.Undefined ();
336- }
337-
338- constexpr size_t CHUNK_SIZE = 64 * 1024 ;
339- const auto copyInto = [state](std::byte* destination, size_t outputLength) {
340- auto segmentIndex = state->SegmentIndex ;
341- auto segmentOffset = state->SegmentOffset ;
342- size_t remaining = outputLength;
343-
344- while (remaining > 0 )
345- {
346- const auto & segment = state->BlobData ->Segments [segmentIndex];
347- const auto copyLength = std::min (segment.Length - segmentOffset, remaining);
348- std::memcpy (destination, segment.Bytes ->data () + segment.Offset + segmentOffset, copyLength);
349- destination += copyLength;
350- remaining -= copyLength;
351- segmentOffset += copyLength;
352- if (segmentOffset == segment.Length )
353- {
354- ++segmentIndex;
355- segmentOffset = 0 ;
356- }
357- }
358-
359- state->Position += outputLength;
360- state->SegmentIndex = segmentIndex;
361- state->SegmentOffset = segmentOffset;
362- };
363-
364- const auto byobRequestValue = controller.Get (" byobRequest" );
365- if (!byobRequestValue.IsUndefined () && !byobRequestValue.IsNull ())
366- {
367- const auto byobRequest = byobRequestValue.As <Napi::Object>();
368- const auto viewValue = byobRequest.Get (" view" );
369- if (!viewValue.IsTypedArray ())
370- {
371- throw Napi::TypeError::New (env, " Blob.stream() received an invalid BYOB request view." );
372- }
373-
374- const auto view = viewValue.As <Napi::TypedArray>();
375- const auto outputLength = std::min ({CHUNK_SIZE , view.ByteLength (), state->BlobData ->Size - state->Position });
376- const auto outputBuffer = view.ArrayBuffer ();
377- auto destination = static_cast <std::byte*>(outputBuffer.Data ()) + view.ByteOffset ();
378- copyInto (destination, outputLength);
379- byobRequest.Get (" respond" ).As <Napi::Function>().Call (byobRequest, {Napi::Number::New (env, outputLength)});
380- }
381- else
382- {
383- const auto outputLength = std::min (CHUNK_SIZE , state->BlobData ->Size - state->Position );
384- auto outputBuffer = Napi::ArrayBuffer::New (env, outputLength);
385- copyInto (static_cast <std::byte*>(outputBuffer.Data ()), outputLength);
386- auto output = Napi::Uint8Array::New (env, outputLength, outputBuffer, 0 );
387- controller.Get (" enqueue" ).As <Napi::Function>().Call (controller, {output});
388- }
389-
390- if (state->Position == state->BlobData ->Size )
391- {
392- controller.Get (" close" ).As <Napi::Function>().Call (controller, {});
393- state->BlobData .reset ();
394- }
395-
396- return env.Undefined ();
397- }
398-
399- Napi::Value Blob::CancelStream (const Napi::CallbackInfo& info)
400- {
401- static_cast <StreamState*>(info.Data ())->BlobData .reset ();
402- return info.Env ().Undefined ();
403- }
404-
405423 bool Blob::AppendBlobPart (Storage& data, const Napi::Value& blobPart)
406424 {
407425 const std::byte* source{};
0 commit comments