-
Notifications
You must be signed in to change notification settings - Fork 252
/
standard.h
1263 lines (985 loc) · 46.4 KB
/
standard.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2017-2022 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
// https://opensource.org/licenses/Apache-2.0
#pragma once
#include "common.h"
#include "internal.h"
#include "queue.h"
#include <workerd/jsg/function.h>
#include <workerd/jsg/buffersource.h>
namespace workerd::api {
class ReadableStreamDefaultController;
class ReadableByteStreamController;
class WritableStreamDefaultController;
class TransformStreamDefaultController;
struct StreamQueuingStrategy {
using SizeAlgorithm = uint64_t(v8::Local<v8::Value>);
jsg::Optional<uint64_t> highWaterMark;
jsg::Optional<jsg::Function<SizeAlgorithm>> size;
JSG_STRUCT(highWaterMark, size);
};
struct UnderlyingSource {
using Controller = kj::OneOf<jsg::Ref<ReadableStreamDefaultController>,
jsg::Ref<ReadableByteStreamController>>;
using StartAlgorithm = jsg::Promise<void>(Controller);
using PullAlgorithm = jsg::Promise<void>(Controller);
using CancelAlgorithm = jsg::Promise<void>(v8::Local<v8::Value> reason);
static constexpr int DEFAULT_AUTO_ALLOCATE_CHUNK_SIZE = 4096;
// The autoAllocateChunkSize mechanism allows byte streams to operate as if a BYOB
// reader is being used even if it is just a default reader. Support is optional
// per the streams spec but our implementation will always enable it. Specifically,
// if user code does not provide an explicit autoAllocateChunkSize, we'll assume
// this default.
jsg::Optional<kj::String> type;
// Per the spec, the type property for the UnderlyingSource should be either
// undefined, the empty string, or "bytes". When undefined, the empty string is
// used as the default. When type is the empty string, the stream is considered
// to be value-oriented rather than byte-oriented.
jsg::Optional<int> autoAllocateChunkSize;
// Used only when type is equal to "bytes", the autoAllocateChunkSize defines
// the size of automatically allocated buffer that is created when a default
// mode read is performed on a byte-oriented ReadableStream that supports
// BYOB reads. The stream standard makes this optional to support and defines
// no default value. We've chosen to use a default value of 4096. If given,
// the value must be greater than zero.
jsg::Optional<jsg::Function<StartAlgorithm>> start;
jsg::Optional<jsg::Function<PullAlgorithm>> pull;
jsg::Optional<jsg::Function<CancelAlgorithm>> cancel;
JSG_STRUCT(type, autoAllocateChunkSize, start, pull, cancel);
kj::Maybe<jsg::Ref<TransformStreamDefaultController>> maybeTransformer;
// The maybeTransformer field here is part of the internal implementation of
// TransformStream. Specifically, this field is not exposed to JavaScript.
};
struct UnderlyingSink {
using Controller = jsg::Ref<WritableStreamDefaultController>;
using StartAlgorithm = jsg::Promise<void>(Controller);
using WriteAlgorithm = jsg::Promise<void>(v8::Local<v8::Value>, Controller);
using AbortAlgorithm = jsg::Promise<void>(v8::Local<v8::Value> reason);
using CloseAlgorithm = jsg::Promise<void>();
jsg::Optional<kj::String> type;
// Per the spec, the type property for the UnderlyingSink should always be either
// undefined or the empty string. Any other value will trigger a TypeError.
jsg::Optional<jsg::Function<StartAlgorithm>> start;
jsg::Optional<jsg::Function<WriteAlgorithm>> write;
jsg::Optional<jsg::Function<AbortAlgorithm>> abort;
jsg::Optional<jsg::Function<CloseAlgorithm>> close;
JSG_STRUCT(type, start, write, abort, close);
kj::Maybe<jsg::Ref<TransformStreamDefaultController>> maybeTransformer;
// The maybeTransformer field here is part of the internal implementation of
// TransformStream. Specifically, this field is not exposed to JavaScript.
};
struct Transformer {
using Controller = jsg::Ref<TransformStreamDefaultController>;
using StartAlgorithm = jsg::Promise<void>(Controller);
using TransformAlgorithm = jsg::Promise<void>(v8::Local<v8::Value>, Controller);
using FlushAlgorithm = jsg::Promise<void>(Controller);
jsg::Optional<kj::String> readableType;
jsg::Optional<kj::String> writableType;
jsg::Optional<jsg::Function<StartAlgorithm>> start;
jsg::Optional<jsg::Function<TransformAlgorithm>> transform;
jsg::Optional<jsg::Function<FlushAlgorithm>> flush;
JSG_STRUCT(readableType, writableType, start, transform, flush);
};
// =======================================================================================
// jscontroller, ReadableStreamJsController, WritableStreamJsController, and the rest in
// this section define the implementation of JavaScript-backed ReadableStream and WritableStreams.
//
// A JavaScript-backed ReadableStream is backed by a ReadableStreamJsController that is either
// Closed, Errored, or in a Readable state. When readable, the controller owns either a
// ReadableStreamDefaultController or ReadableByteStreamController object that corresponds
// to the identically named interfaces in the streams spec. These objects are responsible
// for the bulk of the implementation detail, with the ReadableStreamJsController serving
// only as a bridge between it and the ReadableStream object itself.
//
// * ReadableStream -> ReadableStreamJsController -> jsg::Ref<ReadableStreamDefaultController>
// * ReadableStream -> ReadableStreamJsController -> jsg::Ref<ReadableByteStreamController>
//
// Contrast this with the implementation of internal streams using the
// ReadableStreamInternalController:
//
// * ReadableStream -> ReadableStreamInternalController -> IoOwn<ReadableStreamSource>
//
// When user-code creates a JavaScript-backed ReadableStream using the `ReadableStream`
// object constructor, they pass along an object called an "underlying source" that provides
// JavaScript functions the ReadableStream will call to either initialize, close, or source
// the data for the stream:
//
// const readable = new ReadableStream({
// async start(controller) {
// // Initialize the stream
// },
// async pull(controller) {
// // Provide the stream data
// },
// async cancel(reason) {
// // Cancel and de-initialize the stream
// }
// });
//
// By default, a JavaScript-backed ReadableStream is value-oriented -- that is, any JavaScript
// type can be passed through the stream. It is not limited to bytes only. The implementation
// of the pull method on the underlying source can push strings, booleans, numbers, even undefined
// as values that can be read from the stream. In such streams, the `controller` used internally
// (and owned by the ReadableStreamJsController) is the `ReadableStreamDefaultController`.
//
// To create a byte-oriented stream -- one that is capable only of working with bytes in the
// form of ArrayBufferViews (e.g. `Uint8Array`, `Uint16Array`, `DataView`, etc), the underlying
// source object passed into the `ReadableStream` constructor must have a property
// `'type' = 'bytes'`.
//
// const readable = new ReadableStream({
// type: 'bytes',
// async start(controller) {
// // Initialize the stream
// },
// async pull(controller) {
// // Provide the stream data
// },
// async cancel(reason) {
// // Cancel and de-initialize the stream
// }
// });
//
// From here on, we'll refer to these as either value streams or byte streams. And we'll refer to
// ReadableStreamDefaultController as simply "DefaultController", and ReadableByteStreamController
// as simply "ByobController".
//
// The DefaultController and ByobController each maintain an internal queue. When a read request
// is received, if there is enough data in the internal queue to fulfill the read request, then
// we do so. Otherwise, the controller will call the underlying source's pull method to ask it
// to provide data to fulfill the read request.
//
// A critical aspect of the implementation here is that for JavaScript-backed streams, the entire
// implementation never leaves the isolate lock, and we use JavaScript promises (via jsg::Promise)
// instead of kj::Promise's to keep the implementation from having to bounce back and forth between
// the two spaces. This means that with a JavaScript-backed ReadableStream, it is possible to read
// and fully consume the stream entirely from within JavaScript without ever engaging the kj event
// loop.
//
// When you tee() a JavaScript-backed ReadableStream, the stream is put into a locked state and
// the data is funneled out through two separate "branches" (two new `ReadableStream`s).
//
// When anything reads from a tee branch, the underlying controller is asked to read from the
// underlying source. When the underlying source responds to that read request, the
// data is forwarded to all of the known branches.
//
// All of this works great from within JavaScript, but what about when you want to use a
// JavaScript-backed ReadableStream to respond to a fetch request? Or interface it at all
// with any of the existing internal streams that are based on the older ReadableStreamSource
// API. For those cases, ReadableStreamJsController implements the `removeSource()` method to
// acquire a `ReadableStreamJsSource` that wraps the JavaScript controller.
//
// The `ReadableStreamJsSource` implements the internal ReadableStreamSource API.
//
// Whenever tryRead is invoked this source, it will attempt to acquire an isolate lock within
// which it will interface with the JavaScript-backed underlying controller.
// Value streams can be used only so long as the only values they pass along happen to be
// interpretable as bytes (so ArrayBufferViews and ArrayBuffers). These support the minimal
// contract of tryRead including support for the minBytes argument, performing multiple reads
// on the underlying controller if necessary, as efficiently as possible within a single
// isolate lock.
//
// The story for JavaScript-backed writable streams is similar. User code passes what the
// spec calls an "underlying sink" to the `WritableStream` object constructor. This provides
// functions that are used to receive stream data.
//
// const writable = new WritableStream({
// async start(controller) {
// // initialize
// },
// async write(chunk, controller) {
// // process the written chunk
// },
// async abort(reason) {},
// async close(reason) {},
// });
//
// It is important to note that JavaScript-backed WritableStream's are *always* value
// oriented. It is up to the implementation of the underlying sink to determine if it is
// capable of doing anything with whatever type of chunk it is given.
//
// JavaScript-backed WritableStreams are backed by the WritableStreamJsController and
// WritableStreamDefaultController objects:
//
// WritableStream -> WritableStreamJsController -> jsg::Ref<WritableStreamDefaultController>
//
// The WritableStreamJsController implements both the WritableStreamController interface
// (same API that is implemented by WritableStreamInternalController) and the
// jscontroller::WriterOwner API.
//
// All write operations on a JavaScript-backed WritableStream are processed within the
// isolate lock using JavaScript promises instead of kj::Promises.
struct ValueReadable;
struct ByteReadable;
KJ_DECLARE_NON_POLYMORPHIC(ValueReadable);
KJ_DECLARE_NON_POLYMORPHIC(ByteReadable);
namespace jscontroller {
// The jscontroller namespace defines declarations that are common to all of the the
// JavaScript-backed ReadableStream and WritableStream variants.
using CloseRequest = jsg::Promise<void>::Resolver;
using DefaultController = jsg::Ref<ReadableStreamDefaultController>;
using ByobController = jsg::Ref<ReadableByteStreamController>;
// =======================================================================================
// ReadableStreams can be either Closed, Errored, or Readable.
// WritableStreams can be either Closed, Errored, Erroring, or Writable.
struct Writable {};
// =======================================================================================
// The Unlocked, Locked, ReaderLocked, and WriterLocked structs
// are used to track the current lock status of JavaScript-backed streams.
// All readable and writable streams begin in the Unlocked state. When a
// reader or writer are attached, the streams will transition into the
// ReaderLocked or WriterLocked state. When the reader is released, those
// will transition back to Unlocked.
//
// When a readable is piped to a writable, both will enter the PipeLocked state.
// (PipeLocked is defined within the ReadableLockImpl and WritableLockImpl classes
// below) When the pipe completes, both will transition back to Unlocked.
//
// When either the removeSource() or removeSink() methods are called, the streams
// will transition to the Locked state.
//
// When a ReadableStreamJsController is tee()'d, it will enter the locked state.
template <typename Controller>
class ReadableLockImpl {
// A utility class used by ReadableStreamJsController
// for implementing the reader lock in a consistent way (without duplicating any code).
public:
using PipeController = ReadableStreamController::PipeController;
using Reader = ReadableStreamController::Reader;
bool isLockedToReader() const { return !state.template is<Unlocked>(); }
bool lockReader(jsg::Lock& js, Controller& self, Reader& reader);
void releaseReader(Controller& self, Reader& reader, kj::Maybe<jsg::Lock&> maybeJs);
// See the comment for releaseReader in common.h for details on the use of maybeJs
void onClose();
void onError(jsg::Lock& js, v8::Local<v8::Value> reason);
kj::Maybe<PipeController&> tryPipeLock(
Controller& self,
jsg::Ref<WritableStream> destination);
void visitForGc(jsg::GcVisitor& visitor);
private:
class PipeLocked: public PipeController {
public:
explicit PipeLocked(Controller& inner, jsg::Ref<WritableStream> ref)
: inner(inner), writableStreamRef(kj::mv(ref)) {}
bool isClosed() override { return inner.state.template is<StreamStates::Closed>(); }
kj::Maybe<v8::Local<v8::Value>> tryGetErrored(jsg::Lock& js) override {
KJ_IF_MAYBE(errored, inner.state.template tryGet<StreamStates::Errored>()) {
return errored->getHandle(js);
}
return nullptr;
}
void cancel(jsg::Lock& js, v8::Local<v8::Value> reason) override {
// Cancel here returns a Promise but we do not need to propagate it.
// We can safely drop it on the floor here.
auto promise KJ_UNUSED = inner.cancel(js, reason);
}
void close() override {
inner.doClose();
}
void error(jsg::Lock& js, v8::Local<v8::Value> reason) override {
inner.doError(js, reason);
}
void release(jsg::Lock& js,
kj::Maybe<v8::Local<v8::Value>> maybeError = nullptr) override {
KJ_IF_MAYBE(error, maybeError) {
cancel(js, *error);
}
inner.lock.state.template init<Unlocked>();
}
kj::Maybe<kj::Promise<void>> tryPumpTo(WritableStreamSink& sink, bool end) override;
jsg::Promise<ReadResult> read(jsg::Lock& js) override;
void visitForGc(jsg::GcVisitor& visitor) ;
private:
Controller& inner;
jsg::Ref<WritableStream> writableStreamRef;
friend Controller;
};
kj::OneOf<Locked, PipeLocked, ReaderLocked, Unlocked> state = Unlocked();
friend Controller;
};
template <typename Controller>
class WritableLockImpl {
// A utility class used by WritableStreamJsController to implement the writer lock
// mechanism. Extracted for consistency with ReadableStreamJsController and to
// eventually allow it to be shared also with WritableStreamInternalController.
public:
using Writer = WritableStreamController::Writer;
bool isLockedToWriter() const;
bool lockWriter(jsg::Lock& js, Controller& self, Writer& writer);
void releaseWriter(Controller& self, Writer& writer, kj::Maybe<jsg::Lock&> maybeJs);
// See the comment for releaseWriter in common.h for details on the use of maybeJs
void visitForGc(jsg::GcVisitor& visitor);
bool pipeLock(WritableStream& owner,
jsg::Ref<ReadableStream> source,
PipeToOptions& options);
void releasePipeLock();
private:
struct PipeLocked {
ReadableStreamController::PipeController& source;
jsg::Ref<ReadableStream> readableStreamRef;
bool preventAbort;
bool preventCancel;
bool preventClose;
bool pipeThrough;
kj::Maybe<jsg::Ref<AbortSignal>> maybeSignal;
kj::Maybe<jsg::Promise<void>> checkSignal(
jsg::Lock& js,
Controller& self);
};
kj::OneOf<Unlocked, Locked, WriterLocked, PipeLocked> state = Unlocked();
inline PipeLocked& getPipe() {
return KJ_ASSERT_NONNULL(state.template tryGet<PipeLocked>());
}
friend Controller;
};
// =======================================================================================
class WriterOwner {
// The WriterOwner is the current owner of a WritableStreamDefaultcontroller.
// Currently, this can only be a WritableStreamJsController.
// The WriterOwner interface allows the underlying controller to communicate
// status updates up to the current owner without caring about what kind of thing
// the owner currently is.
public:
virtual void doClose() = 0;
// Communicate to the owner that the stream has been closed. The owner should release
// ownership of the underlying controller and allow it to be garbage collected as soon
// as possible.
virtual void doError(jsg::Lock& js, v8::Local<v8::Value> reason) = 0;
// Communicate to the owner that the stream has been errored. The owner should remember
// the error reason, and release ownership of the underlying controller and allow it to
// be garbage collected as soon as possible.
virtual bool isLocked() const = 0;
virtual void updateBackpressure(jsg::Lock& js, bool backpressure) = 0;
virtual void maybeResolveReadyPromise() = 0;
virtual void maybeRejectReadyPromise(jsg::Lock& js, v8::Local<v8::Value> reason) = 0;
};
// =======================================================================================
template <class Self>
class ReadableImpl {
// The ReadableImpl provides implementation that is common to both the
// ReadableStreamDefaultController and the ReadableByteStreamController.
public:
using Consumer = typename Self::QueueType::Consumer;
using Entry = typename Self::QueueType::Entry;
using StateListener = typename Self::QueueType::ConsumerImpl::StateListener;
ReadableImpl(UnderlyingSource underlyingSource,
StreamQueuingStrategy queuingStrategy);
void start(jsg::Lock& js, jsg::Ref<Self> self);
jsg::Promise<void> cancel(jsg::Lock& js,
jsg::Ref<Self> self,
v8::Local<v8::Value> maybeReason);
bool canCloseOrEnqueue();
void doCancel(jsg::Lock& js, jsg::Ref<Self> self, v8::Local<v8::Value> reason);
void close(jsg::Lock& js);
void enqueue(jsg::Lock& js, kj::Own<Entry> entry, jsg::Ref<Self> self);
void doClose(jsg::Lock& js);
void doError(jsg::Lock& js, jsg::Value reason);
kj::Maybe<int> getDesiredSize();
void pullIfNeeded(jsg::Lock& js, jsg::Ref<Self> self);
bool hasPendingReadRequests();
bool shouldCallPull();
kj::Own<Consumer> getConsumer(kj::Maybe<StateListener&> listener);
void visitForGc(jsg::GcVisitor& visitor);
private:
struct Algorithms {
kj::Maybe<jsg::Promise<void>> starting;
kj::Maybe<jsg::Promise<void>> pulling;
kj::Maybe<jsg::Promise<void>> canceling;
kj::Maybe<jsg::Function<UnderlyingSource::StartAlgorithm>> start;
kj::Maybe<jsg::Function<UnderlyingSource::PullAlgorithm>> pull;
kj::Maybe<jsg::Function<UnderlyingSource::CancelAlgorithm>> cancel;
kj::Maybe<jsg::Function<StreamQueuingStrategy::SizeAlgorithm>> size;
Algorithms(UnderlyingSource underlyingSource, StreamQueuingStrategy queuingStrategy)
: start(kj::mv(underlyingSource.start)),
pull(kj::mv(underlyingSource.pull)),
cancel(kj::mv(underlyingSource.cancel)),
size(kj::mv(queuingStrategy.size)) {}
Algorithms(Algorithms&& other) = default;
Algorithms& operator=(Algorithms&& other) = default;
void clear() {
starting = nullptr;
pulling = nullptr;
canceling = nullptr;
start = nullptr;
pull = nullptr;
cancel = nullptr;
size = nullptr;
}
void visitForGc(jsg::GcVisitor& visitor) {
visitor.visit(starting, pulling, canceling, start, pull, cancel, size);
}
};
using Queue = typename Self::QueueType;
kj::OneOf<StreamStates::Closed, StreamStates::Errored, Queue> state;
Algorithms algorithms;
bool closeRequested = false;
bool disturbed = false;
bool pullAgain = false;
bool pulling = false;
bool started = false;
size_t highWaterMark = 1;
struct PendingCancel {
kj::Maybe<jsg::Promise<void>::Resolver> fulfiller;
jsg::Promise<void> promise;
};
kj::Maybe<PendingCancel> maybePendingCancel;
friend Self;
};
template <class Self>
class WritableImpl {
// Utility that provides the core implementation of WritableStreamJsController,
// separated out for consistency with ReadableStreamJsController/ReadableImpl and
// to enable it to be more easily reused should new kinds of WritableStream
// controllers be introduced.
public:
using PendingAbort = WritableStreamController::PendingAbort;
struct WriteRequest {
jsg::Promise<void>::Resolver resolver;
jsg::Value value;
size_t size;
void visitForGc(jsg::GcVisitor& visitor) {
visitor.visit(resolver, value);
}
};
WritableImpl(WriterOwner& owner);
jsg::Promise<void> abort(jsg::Lock& js,
jsg::Ref<Self> self,
v8::Local<v8::Value> reason);
void advanceQueueIfNeeded(jsg::Lock& js, jsg::Ref<Self> self);
jsg::Promise<void> close(jsg::Lock& js, jsg::Ref<Self> self);
void dealWithRejection(jsg::Lock& js, jsg::Ref<Self> self, v8::Local<v8::Value> reason);
WriteRequest dequeueWriteRequest();
void doClose();
void doError(jsg::Lock& js, v8::Local<v8::Value> reason);
void error(jsg::Lock& js, jsg::Ref<Self> self, v8::Local<v8::Value> reason);
void finishErroring(jsg::Lock& js, jsg::Ref<Self> self);
void finishInFlightClose(
jsg::Lock& js,
jsg::Ref<Self> self,
kj::Maybe<v8::Local<v8::Value>> reason = nullptr);
void finishInFlightWrite(
jsg::Lock& js,
jsg::Ref<Self> self,
kj::Maybe<v8::Local<v8::Value>> reason = nullptr);
ssize_t getDesiredSize();
bool isCloseQueuedOrInFlight();
void rejectCloseAndClosedPromiseIfNeeded(jsg::Lock& js);
void setOwner(kj::Maybe<WriterOwner&> owner) {
this->owner = owner;
}
WriterOwner& getOwner() {
return JSG_REQUIRE_NONNULL(owner, TypeError, "This stream has been closed.");
}
void setup(
jsg::Lock& js,
jsg::Ref<Self> self,
UnderlyingSink underlyingSink,
StreamQueuingStrategy queuingStrategy);
void startErroring(jsg::Lock& js, jsg::Ref<Self> self, v8::Local<v8::Value> reason);
void updateBackpressure(jsg::Lock& js);
jsg::Promise<void> write(jsg::Lock& js, jsg::Ref<Self> self, v8::Local<v8::Value> value);
void visitForGc(jsg::GcVisitor& visitor);
private:
struct Algorithms {
kj::Maybe<jsg::Promise<void>> aborting;
kj::Maybe<jsg::Promise<void>> closing;
kj::Maybe<jsg::Promise<void>> starting;
kj::Maybe<jsg::Promise<void>> writing;
kj::Maybe<jsg::Function<UnderlyingSink::AbortAlgorithm>> abort;
kj::Maybe<jsg::Function<UnderlyingSink::CloseAlgorithm>> close;
kj::Maybe<jsg::Function<UnderlyingSink::WriteAlgorithm>> write;
kj::Maybe<jsg::Function<StreamQueuingStrategy::SizeAlgorithm>> size;
Algorithms() {};
Algorithms(Algorithms&& other) = default;
Algorithms& operator=(Algorithms&& other) = default;
void clear() {
aborting = nullptr;
closing = nullptr;
starting = nullptr;
writing = nullptr;
abort = nullptr;
close = nullptr;
size = nullptr;
write = nullptr;
}
void visitForGc(jsg::GcVisitor& visitor) {
visitor.visit(starting, aborting, closing, writing, write, close, abort, size);
}
};
kj::Maybe<WriterOwner&> owner;
jsg::Ref<AbortSignal> signal;
kj::OneOf<StreamStates::Closed,
StreamStates::Errored,
StreamStates::Erroring,
Writable> state = Writable();
Algorithms algorithms;
bool started = false;
bool backpressure = false;
size_t highWaterMark = 1;
std::deque<WriteRequest> writeRequests;
size_t amountBuffered = 0;
kj::Maybe<WriteRequest> inFlightWrite;
kj::Maybe<CloseRequest> inFlightClose;
kj::Maybe<CloseRequest> closeRequest;
kj::Maybe<PendingAbort> maybePendingAbort;
friend Self;
};
} // namespace jscontroller
// =======================================================================================
class ReadableStreamDefaultController: public jsg::Object {
// ReadableStreamDefaultController is a JavaScript object defined by the streams specification.
// It is capable of streaming any JavaScript value through it, including typed arrays and
// array buffers, but treats all values as opaque. BYOB reads are not supported.
public:
using QueueType = ValueQueue;
using ReadableImpl = jscontroller::ReadableImpl<ReadableStreamDefaultController>;
ReadableStreamDefaultController(UnderlyingSource underlyingSource,
StreamQueuingStrategy queuingStrategy);
void start(jsg::Lock& js);
jsg::Promise<void> cancel(jsg::Lock& js,
jsg::Optional<v8::Local<v8::Value>> maybeReason);
void close(jsg::Lock& js);
bool canCloseOrEnqueue();
bool hasBackpressure();
kj::Maybe<int> getDesiredSize();
bool hasPendingReadRequests();
void enqueue(jsg::Lock& js, jsg::Optional<v8::Local<v8::Value>> chunk);
void error(jsg::Lock& js, v8::Local<v8::Value> reason);
void pull(jsg::Lock& js);
kj::Own<ValueQueue::Consumer> getConsumer(
kj::Maybe<ValueQueue::ConsumerImpl::StateListener&> stateListener);
JSG_RESOURCE_TYPE(ReadableStreamDefaultController) {
JSG_READONLY_INSTANCE_PROPERTY(desiredSize, getDesiredSize);
JSG_METHOD(close);
JSG_METHOD(enqueue);
JSG_METHOD(error);
}
private:
ReadableImpl impl;
void visitForGc(jsg::GcVisitor& visitor);
};
class ReadableStreamBYOBRequest: public jsg::Object {
// The ReadableStreamBYOBRequest is provided by the ReadableByteStreamController
// and is used by user code to fill a view provided by a BYOB read request.
// Because we always support autoAllocateChunkSize in the ReadableByteStreamController,
// there will always be a ReadableStreamBYOBRequest available when there is a pending
// read.
//
// The ReadableStreamBYOBRequest is either in an attached or detached state.
// The request is detached when invalidate() is called. Attempts to use the request
// after it has been detached will fail.
//
// Note that the casing of the name (e.g. "BYOB" instead of the kj style "Byob") is
// dictated by the streams specification since the class name is used as the exported
// object name.
public:
ReadableStreamBYOBRequest(
jsg::Lock& js,
kj::Own<ByteQueue::ByobRequest> readRequest,
jsg::Ref<ReadableByteStreamController> controller);
KJ_DISALLOW_COPY(ReadableStreamBYOBRequest);
ReadableStreamBYOBRequest(ReadableStreamBYOBRequest&&) = delete;
ReadableStreamBYOBRequest& operator=(ReadableStreamBYOBRequest&&) = delete;
kj::Maybe<int> getAtLeast();
// getAtLeast is a non-standard Workers-specific extension that specifies
// the minimum number of bytes the stream should fill into the view. It is
// added to support the readAtLeast extension on the ReadableStreamBYOBReader.
kj::Maybe<jsg::V8Ref<v8::Uint8Array>> getView(jsg::Lock& js);
void invalidate(jsg::Lock& js);
void respond(jsg::Lock& js, int bytesWritten);
void respondWithNewView(jsg::Lock& js, jsg::BufferSource view);
JSG_RESOURCE_TYPE(ReadableStreamBYOBRequest) {
JSG_READONLY_INSTANCE_PROPERTY(view, getView);
JSG_METHOD(respond);
JSG_METHOD(respondWithNewView);
JSG_READONLY_INSTANCE_PROPERTY(atLeast, getAtLeast);
// atLeast is an Workers-specific extension used to support the
// readAtLeast API.
}
private:
struct Impl {
kj::Own<ByteQueue::ByobRequest> readRequest;
jsg::Ref<ReadableByteStreamController> controller;
jsg::V8Ref<v8::Uint8Array> view;
Impl(jsg::Lock& js,
kj::Own<ByteQueue::ByobRequest> readRequest,
jsg::Ref<ReadableByteStreamController> controller)
: readRequest(kj::mv(readRequest)),
controller(kj::mv(controller)),
view(js.v8Ref(this->readRequest->getView(js))) {}
};
kj::Maybe<Impl> maybeImpl;
void visitForGc(jsg::GcVisitor& visitor);
};
class ReadableByteStreamController: public jsg::Object {
// ReadableByteStreamController is a JavaScript object defined by the streams specification.
// It is capable of only streaming byte data through it in the form of typed arrays.
// BYOB reads are supported.
public:
using QueueType = ByteQueue;
using ReadableImpl = jscontroller::ReadableImpl<ReadableByteStreamController>;
ReadableByteStreamController(UnderlyingSource underlyingSource,
StreamQueuingStrategy queuingStrategy);
void start(jsg::Lock& js);
jsg::Promise<void> cancel(jsg::Lock& js,
jsg::Optional<v8::Local<v8::Value>> maybeReason);
void close(jsg::Lock& js);
void enqueue(jsg::Lock& js, jsg::BufferSource chunk);
void error(jsg::Lock& js, v8::Local<v8::Value> reason);
bool canCloseOrEnqueue();
bool hasBackpressure();
kj::Maybe<int> getDesiredSize();
bool hasPendingReadRequests();
kj::Maybe<jsg::Ref<ReadableStreamBYOBRequest>> getByobRequest(jsg::Lock& js);
void pull(jsg::Lock& js);
kj::Own<ByteQueue::Consumer> getConsumer(
kj::Maybe<ByteQueue::ConsumerImpl::StateListener&> stateListener);
JSG_RESOURCE_TYPE(ReadableByteStreamController) {
JSG_READONLY_INSTANCE_PROPERTY(byobRequest, getByobRequest);
JSG_READONLY_INSTANCE_PROPERTY(desiredSize, getDesiredSize);
JSG_METHOD(close);
JSG_METHOD(enqueue);
JSG_METHOD(error);
}
private:
ReadableImpl impl;
kj::Maybe<jsg::Ref<ReadableStreamBYOBRequest>> maybeByobRequest;
void visitForGc(jsg::GcVisitor& visitor);
friend class ReadableStreamBYOBRequest;
friend class ReadableStreamJsController;
};
class ReadableStreamJsController: public ReadableStreamController {
// The ReadableStreamJsController provides the implementation of custom
// ReadableStreams backed by a user-code provided Underlying Source. The implementation
// is fairly complicated and defined entirely by the streams specification.
//
// One critically important aspect of this controller is that unless removeSource
// is called to acquire a ReadableStreamSource from this controller, the entire
// implementation operates completely within the JavaScript side within the isolate
// lock.
//
// Another important thing to understand is that there are two types of JavaScript
// backed ReadableStreams: value-oriented, and byte-oriented.
//
// When user code uses the `new ReadableStream(underlyingSource)` constructor, the
// underlyingSource argument may have a `type` property, the value of which is either
// `undefined`, the empty string, or the string value `'bytes'`. If the underlyingSource
// argument is not given, the default value of `type` is `undefined`. If `type` is
// `undefined` or the empty string, the ReadableStream is value-oriented. If `type` is
// exactly equal to `'bytes'`, the ReadableStream is byte-oriented.
//
// For value-oriented streams, any JavaScript value can be pushed through the stream,
// and the stream will only support use of the ReadableStreamDefaultReader to consume
// the stream data.
//
// For byte-oriented streams, only byte data (as provided by `ArrayBufferView`s) can
// be pushed through the stream. All byte-oriented streams support using both
// ReadableStreamDefaultReader and ReadableStreamBYOBReader to consume the stream
// data.
//
// When the ReadableStreamJsController::setup() method is called the type
// of stream is determined, and the controller will create an instance of either
// jsg::Ref<ReadableStreamDefaultController> or jsg::Ref<ReadableByteStreamController>.
// These are the objects that are actually passed on to the user-code's Underlying Source
// implementation.
public:
using ByobController = jscontroller::ByobController;
using DefaultController = jscontroller::DefaultController;
using ReadableLockImpl = jscontroller::ReadableLockImpl<ReadableStreamJsController>;
explicit ReadableStreamJsController() = default;
ReadableStreamJsController(ReadableStreamJsController&& other) = default;
ReadableStreamJsController& operator=(ReadableStreamJsController&& other) = default;
explicit ReadableStreamJsController(StreamStates::Closed closed);
explicit ReadableStreamJsController(StreamStates::Errored errored);
explicit ReadableStreamJsController(jsg::Lock& js, ValueReadable& consumer);
explicit ReadableStreamJsController(jsg::Lock& js, ByteReadable& consumer);
explicit ReadableStreamJsController(kj::Own<ValueReadable> consumer);
explicit ReadableStreamJsController(kj::Own<ByteReadable> consumer);
jsg::Ref<ReadableStream> addRef() override;
void setup(
jsg::Lock& js,
jsg::Optional<UnderlyingSource> maybeUnderlyingSource,
jsg::Optional<StreamQueuingStrategy> maybeQueuingStrategy);
jsg::Promise<void> cancel(
jsg::Lock& js,
jsg::Optional<v8::Local<v8::Value>> reason) override;
// Signals that this ReadableStream is no longer interested in the underlying
// data source. Whether this cancels the underlying data source also depends
// on whether or not there are other ReadableStreams still attached to it.
// This operation is terminal. Once called, even while the returned Promise
// is still pending, the ReadableStream will be no longer usable and any
// data still in the queue will be dropped. Pending read requests will be
// rejected if a reason is given, or resolved with no data otherwise.
void doClose();
void doError(jsg::Lock& js, v8::Local<v8::Value> reason);
bool canCloseOrEnqueue();
bool hasBackpressure();
bool isByteOriented() const override;
bool isDisturbed() override;
bool isClosedOrErrored() const override;
bool isLockedToReader() const override;
bool lockReader(jsg::Lock& js, Reader& reader) override;
kj::Maybe<v8::Local<v8::Value>> isErrored(jsg::Lock& js);
kj::Maybe<int> getDesiredSize();
jsg::Promise<void> pipeTo(
jsg::Lock& js,
WritableStreamController& destination,
PipeToOptions options) override;
kj::Maybe<jsg::Promise<ReadResult>> read(
jsg::Lock& js,
kj::Maybe<ByobOptions> byobOptions) override;
void releaseReader(Reader& reader, kj::Maybe<jsg::Lock&> maybeJs) override;
// See the comment for releaseReader in common.h for details on the use of maybeJs
kj::Maybe<kj::Own<ReadableStreamSource>> removeSource(jsg::Lock& js) override;
void setOwnerRef(ReadableStream& stream) override;
Tee tee(jsg::Lock& js) override;
kj::Maybe<PipeController&> tryPipeLock(jsg::Ref<WritableStream> destination) override;
void visitForGc(jsg::GcVisitor& visitor) override;
kj::Maybe<kj::OneOf<DefaultController, ByobController>> getController();
private:
bool hasPendingReadRequests();
kj::Maybe<ReadableStream&> owner;
kj::OneOf<StreamStates::Closed,
StreamStates::Errored,
kj::Own<ValueReadable>,
kj::Own<ByteReadable>> state = StreamStates::Closed();
ReadableLockImpl lock;
// The lock state is separate because a closed or errored stream can still be locked.
kj::Maybe<jsg::Ref<TransformStreamDefaultController>> maybeTransformer;
bool disturbed = false;
friend ReadableLockImpl;
friend ReadableLockImpl::PipeLocked;
};
class ReadableStreamJsSource: public kj::Refcounted,
public ReadableStreamSource {
// The ReadableStreamJsSource is a bridge between the JavaScript-backed
// streams and the existing native internal streams. When an instance is
// retrieved from the ReadableStreamJsController, it takes over ownership of the
// ReadableStreamDefaultController or ReadableByteStreamController and takes over
// all interaction with them.
//
// The ReadableStreamDefaultController can be used only so long as the JavaScript
// code only enqueues ArrayBufferView or ArrayBuffer values. Everything else will
// cause tryRead to fail because ReadableStreamSource is only designed to support
// byte data.
//
// When using a ReadableByteStreamController, tryRead acts like a regular BYOB read.
// A single read operation is performed on the controller passing in the buffer, and
// the controller is expected to fill it in as much as possible.
//
// When using a ReadableStreamDefaultController, it gets a bit more complicated. If the
// controller returns a value that cannot be intrepreted as bytes, then the source errors
// and the read promise is rejected.
//
// It is possible for the underlying source to return more bytes than the current read can
// handle. To account for this case, the source maintains an internal byte buffer of its own.
// If the current read can be minimally fulfilled (minBytes) from that buffer, then it is and
// the read promise is resolved synchronously. Otherwise the source will read from the
// controller. If that returns enough data to fulfill the read request, then we're done. Whatever
// extra data it returns is stored in the buffer for the next read. If it does not return enough
// data, we'll keep pulling from the controller until it does or until the controller closes.
public:
explicit ReadableStreamJsSource(StreamStates::Closed closed);
explicit ReadableStreamJsSource(kj::Exception errored);
explicit ReadableStreamJsSource(kj::Own<ValueReadable> consumer);
explicit ReadableStreamJsSource(kj::Own<ByteReadable> consumer);
void doClose();
void doError(jsg::Lock& js, v8::Local<v8::Value> reason);
// ReadableStreamSource implementation
void cancel(kj::Exception reason) override;
kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override;
kj::Promise<DeferredProxy<void>> pumpTo(WritableStreamSink& output, bool end) override;
private:
jsg::Promise<size_t> internalTryRead(
jsg::Lock& js,
void* buffer,
size_t minBytes,