-
Notifications
You must be signed in to change notification settings - Fork 252
/
internal.c++
1891 lines (1645 loc) · 68.9 KB
/
internal.c++
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
#include "internal.h"
#include "readable.h"
#include "writable.h"
#include "transform.h"
#include <workerd/jsg/jsg.h>
namespace workerd::api {
namespace {
[[noreturn]] void throwTypeErrorAndConsoleWarn(kj::StringPtr message) {
// Use this in places where the exception thrown would cause finalizers to run. Your exception
// will not go anywhere, but we'll log the exception message to the console until the problem this
// papers over is fixed.
if (IoContext::hasCurrent()) {
auto& context = IoContext::current();
if (context.isInspectorEnabled()) {
context.logWarning(kj::str(message));
}
}
kj::throwFatalException(
kj::Exception(kj::Exception::Type::FAILED, __FILE__, __LINE__,
kj::str(JSG_EXCEPTION(TypeError) ": ", message)));
}
kj::Promise<void> pumpToHelper(
ReadableStreamSource& input, WritableStreamSink& output, bool end,
kj::Array<kj::byte> bytes) {
auto promise = input.tryRead(bytes.begin(), 1, bytes.size());
return promise.then(
[&input, &output, end, bytes = kj::mv(bytes)]
(size_t amount) mutable
-> kj::Promise<void> {
if (amount == 0) {
if (end) {
return output.end();
} else {
return kj::READY_NOW;
}
}
auto promise = output.write(bytes.begin(), amount);
return promise.then(
[&input, &output, end, bytes = kj::mv(bytes)]() mutable {
return pumpToHelper(input, output, end, kj::mv(bytes));
});
});
}
kj::Promise<void> pumpTo(ReadableStreamSource& input, WritableStreamSink& output, bool end) {
return pumpToHelper(input, output, end, kj::heapArray<kj::byte>(4096));
}
class AllReader {
// Modified from AllReader in kj/async-io.c++.
using PartList = kj::Array<kj::ArrayPtr<byte>>;
public:
explicit AllReader(ReadableStreamSource& input, uint64_t limit)
: input(input), limit(limit) {
JSG_REQUIRE(limit > 0, TypeError, "Memory limit exceeded before EOF.");
KJ_IF_MAYBE(length, input.tryGetLength(StreamEncoding::IDENTITY)) {
// Oh hey, we might be able to bail early.
JSG_REQUIRE(*length < limit, TypeError, "Memory limit would be exceeded before EOF.");
}
}
kj::Promise<kj::Array<byte>> readAllBytes() {
return loop().then([this](PartList&& partPtrs) {
auto out = kj::heapArray<byte>(runningTotal);
copyInto(out, kj::mv(partPtrs));
return kj::mv(out);
});
}
kj::Promise<kj::String> readAllText() {
return loop().then([this](PartList&& partPtrs) {
auto out = kj::heapArray<char>(runningTotal + 1);
copyInto(out.slice(0, out.size() - 1).asBytes(), kj::mv(partPtrs));
out.back() = '\0';
return kj::String(kj::mv(out));
});
}
private:
ReadableStreamSource& input;
uint64_t limit;
kj::Vector<kj::Array<kj::byte>> parts;
uint64_t runningTotal = 0;
kj::Promise<PartList> loop() {
auto bytes = kj::heapArray<kj::byte>(4096);
return input.tryRead(bytes.begin(), 1, bytes.size())
.then([this, bytes = kj::mv(bytes)](size_t amount) mutable
-> kj::Promise<PartList> {
if (amount == 0) {
return KJ_MAP(p, parts) { return p.asPtr(); };
}
runningTotal += amount;
if (runningTotal >= limit) {
return JSG_KJ_EXCEPTION(FAILED, TypeError, "Memory limit exceeded before EOF.");
}
parts.add(bytes.slice(0, amount).attach(kj::mv(bytes)));
return loop();
});
}
void copyInto(kj::ArrayPtr<byte> out, PartList in) {
size_t pos = 0;
for (auto& part: in) {
KJ_ASSERT(part.size() <= out.size() - pos);
memcpy(out.begin() + pos, part.begin(), part.size());
pos += part.size();
}
}
};
kj::Exception reasonToException(
jsg::Lock& js,
jsg::Optional<v8::Local<v8::Value>> maybeReason,
kj::String defaultDescription = kj::str(JSG_EXCEPTION(Error) ": Stream was cancelled.")) {
KJ_IF_MAYBE(reason, maybeReason) {
return js.exceptionToKj(js.v8Ref(*reason));
} else {
// We get here if the caller is something like `r.cancel()` (or `r.cancel(undefined)`).
return kj::Exception(kj::Exception::Type::FAILED, __FILE__, __LINE__,
kj::mv(defaultDescription));
}
}
// =======================================================================================
class TeeAdapter final: public kj::AsyncInputStream {
// Adapt ReadableStreamSource to kj::AsyncInputStream's interface for use with `kj::newTee()`.
public:
explicit TeeAdapter(kj::Own<ReadableStreamSource> inner)
: inner(kj::mv(inner)) {}
kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
return inner->tryRead(buffer, minBytes, maxBytes);
}
kj::Maybe<uint64_t> tryGetLength() override {
return inner->tryGetLength(StreamEncoding::IDENTITY);
}
private:
kj::Own<ReadableStreamSource> inner;
};
class TeeBranch final: public ReadableStreamSource {
public:
explicit TeeBranch(kj::Own<kj::AsyncInputStream> inner)
: inner(kj::mv(inner)) {}
kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
return inner->tryRead(buffer, minBytes, maxBytes);
}
kj::Promise<DeferredProxy<void>> pumpTo(WritableStreamSink& output, bool end) override {
#ifdef KJ_NO_RTTI
// Yes, I'm paranoid.
static_assert(!KJ_NO_RTTI, "Need RTTI for correctness");
#endif
// HACK: If `output` is another TransformStream, we don't allow pumping to it, in order to
// guarantee that we can't create cycles. Note that currently TeeBranch only ever wraps
// TransformStreams, never system streams.
JSG_REQUIRE(kj::dynamicDowncastIfAvailable<IdentityTransformStreamImpl>(output) == nullptr,
TypeError, "Inter-TransformStream ReadableStream.pipeTo() is not implemented.");
// It is important we actually call `inner->pumpTo()` so that `kj::newTee()` is aware of this
// pump operation's backpressure. So we can't use the default `ReadableStreamSource::pumpTo()`
// implementation, and have to implement our own.
auto outputAdapter = kj::heap<PumpAdapter>(output);
auto promise = inner->pumpTo(*outputAdapter).attach(kj::mv(outputAdapter)).ignoreResult();
if (end) {
promise = promise.then([&output]() { return output.end(); });
}
// We only use `TeeBranch` when a locally-sourced stream was tee'd (because system streams
// implement `tryTee()` in a different way that doesn't use `TeeBranch`). So, we know that
// none of the pump can be performed without the IoContext active, and thus
// `DeferredProxy` has to be a noop.
return addNoopDeferredProxy(kj::mv(promise));
}
kj::Maybe<uint64_t> tryGetLength(StreamEncoding encoding) override {
if (encoding == StreamEncoding::IDENTITY) {
return inner->tryGetLength();
} else {
return nullptr;
}
}
kj::Maybe<Tee> tryTee(uint64_t limit) override {
KJ_IF_MAYBE(t, inner->tryTee(limit)) {
auto branch = kj::heap<TeeBranch>(newTeeErrorAdapter(kj::mv(*t)));
auto consumed = kj::heap<TeeBranch>(kj::mv(inner));
return Tee{kj::mv(branch), kj::mv(consumed)};
}
return nullptr;
}
void cancel(kj::Exception reason) override {
// TODO(someday): What to do?
}
private:
class PumpAdapter final: public kj::AsyncOutputStream {
// Adapt WritableStreamSink to kj::AsyncOutputStream's interface for use in
// `TeeBranch::pumpTo()`. If you squint, the write logic looks very similar to TeeAdapter's
// read logic.
public:
explicit PumpAdapter(WritableStreamSink& inner): inner(inner) {}
kj::Promise<void> write(const void* buffer, size_t size) override {
return inner.write(buffer, size);
}
kj::Promise<void> write(kj::ArrayPtr<const kj::ArrayPtr<const byte>> pieces) override {
return inner.write(pieces);
}
kj::Promise<void> whenWriteDisconnected() override {
KJ_UNIMPLEMENTED("whenWriteDisconnected() not expected on PumpAdapter");
}
WritableStreamSink& inner;
};
kj::Own<kj::AsyncInputStream> inner;
};
class WarnIfUnusedStream final: public ReadableStreamSource {
public:
explicit WarnIfUnusedStream(kj::Own<ReadableStreamSource> inner, IoContext& ioContext)
: worker(kj::atomicAddRef(ioContext.getWorker())),
requestMetrics(kj::addRef(ioContext.getMetrics())),
inner(kj::mv(inner)) {}
kj::Promise<DeferredProxy<void>> pumpTo(WritableStreamSink& output, bool end) override {
wasRead = true;
return inner->pumpTo(output, end);
}
kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
wasRead = true;
return inner->tryRead(buffer, minBytes, maxBytes);
}
// TODO(someday): we set `wasRead` to avoid warning here, but TeeBranch might still buffer the body.
// We should fix it not to buffer when cancelled.
void cancel(kj::Exception reason) override {
wasRead = true;
return inner->cancel(reason);
}
// No special behavior, just forward these verbatim.
kj::Maybe<uint64_t> tryGetLength(StreamEncoding encoding) override { return inner->tryGetLength(encoding); }
kj::Maybe<Tee> tryTee(uint64_t limit) override { return inner->tryTee(limit); }
~WarnIfUnusedStream() {
// There's some subtlety here. If WarnIfUnused is being GC'd then we're
// fine; we can use `ctx->logWarning` like normal. However, if this is
// being destroyed at the end of the request then we're in the middle of
// tearing down the whole IoContext. In that case, we do *not* have
// an isolate lock available, and need to take one out. We can't call
// `ctx->isInspectorEnabled` without a lock either, so instead it's stored at
// the time the worker calls `clone()`.
// N.B. It's fine not to call `isInspectorEnabled` here because the
// inspector is either enabled or disabled for the whole lifetime of the
// isolate.
if (!wasRead) {
auto msg =
"Your worker called response.clone(), but did not read the body of both clones. "
"This is wasteful, as it forces the system to buffer the entire response body in memory, "
"rather than streaming it through. This may cause your worker to be unexpectedly "
"terminated for going over the memory limit. If you only meant to copy the "
"response headers and metadata (e.g. in order to be able to modify them), "
"use `new Response(response.body, response)` instead.";
// If possible, give a warning pointing to the line number.
if (IoContext::hasCurrent()) {
// We're currently in a JavaScript execution context, which means the object must be being
// destroyed due to GC. V8 does not like having most of its APIs invoked in the middle of
// GC. So, delay our log warning until GC finishes.
auto& context = IoContext::current();
context.addTask(context.run([msg](Worker::Lock& lock) {
lock.logWarning(kj::str(msg));
}));
} else {
// We aren't in any JavaScript context. The stream might be being destroyed during
// IoContext shutdown or maybe even during deferred proxying. So, avoid touching
// the IoContext. Instead, we'll lock the worker directly.
//
// Synchronous lock is OK here since it only happens during preview. We don't have a
// metrics object to provide ,though.
Worker::Lock lock(*worker, Worker::Lock::TakeSynchronously(*requestMetrics));
lock.logWarning(msg);
}
}
}
private:
kj::Own<const Worker> worker;
kj::Own<RequestObserver> requestMetrics;
kj::Own<ReadableStreamSource> inner;
// Used for tracking if this body was ever used.
bool wasRead = false;
};
} // namespace
// =======================================================================================
kj::Promise<DeferredProxy<void>> ReadableStreamSource::pumpTo(
WritableStreamSink& output, bool end) {
KJ_IF_MAYBE(p, output.tryPumpFrom(*this, end)) {
return kj::mv(*p);
}
// Non-optimized pumpTo() is presumed to require the IoContext to remain live, so don't do
// anything in the deferred proxy part.
return addNoopDeferredProxy(api::pumpTo(*this, output, end));
}
kj::Maybe<uint64_t> ReadableStreamSource::tryGetLength(StreamEncoding encoding) {
return nullptr;
}
kj::Promise<kj::Array<byte>> ReadableStreamSource::readAllBytes(uint64_t limit) {
auto allReader = kj::heap<AllReader>(*this, limit);
return allReader->readAllBytes().attach(kj::mv(allReader));
}
kj::Promise<kj::String> ReadableStreamSource::readAllText(uint64_t limit) {
auto allReader = kj::heap<AllReader>(*this, limit);
return allReader->readAllText().attach(kj::mv(allReader));
}
void ReadableStreamSource::cancel(kj::Exception reason) {}
kj::Maybe<ReadableStreamSource::Tee> ReadableStreamSource::tryTee(uint64_t limit) {
return nullptr;
}
kj::Maybe<kj::Promise<DeferredProxy<void>>> WritableStreamSink::tryPumpFrom(
ReadableStreamSource& input, bool end) {
return nullptr;
}
// =======================================================================================
ReadableStreamInternalController::~ReadableStreamInternalController() noexcept(false) {
KJ_IF_MAYBE(locked, readState.tryGet<ReaderLocked>()) {
auto lock = kj::mv(*locked);
readState.init<Unlocked>();
}
}
jsg::Ref<ReadableStream> ReadableStreamInternalController::addRef() {
return KJ_ASSERT_NONNULL(owner).addRef();
}
kj::Maybe<jsg::Promise<ReadResult>> ReadableStreamInternalController::read(
jsg::Lock& js,
kj::Maybe<ByobOptions> maybeByobOptions) {
std::shared_ptr<v8::BackingStore> store;
size_t byteLength = 0;
size_t byteOffset = 0;
size_t atLeast = 1;
KJ_IF_MAYBE(byobOptions, maybeByobOptions) {
auto buffer = byobOptions->bufferView.getHandle(js)->Buffer();
store = buffer->GetBackingStore();
byteOffset = byobOptions->byteOffset;
byteLength = byobOptions->byteLength;
atLeast = byobOptions->atLeast.orDefault(atLeast);
if (byobOptions->detachBuffer) {
if (!buffer->IsDetachable()) {
return js.rejectedPromise<ReadResult>(
js.v8TypeError("Unable to use non-detachable ArrayBuffer"_kj));
}
buffer->Detach();
}
} else {
byteLength = UnderlyingSource::DEFAULT_AUTO_ALLOCATE_CHUNK_SIZE;
store = v8::ArrayBuffer::NewBackingStore(js.v8Isolate, byteLength);
}
auto bytes = kj::arrayPtr(static_cast<kj::byte*>(store->Data()), byteOffset + byteLength);
disturbed = true;
KJ_SWITCH_ONEOF(state) {
KJ_CASE_ONEOF(closed, StreamStates::Closed) {
return js.resolvedPromise(ReadResult { .done = true });
}
KJ_CASE_ONEOF(errored, StreamStates::Errored) {
return js.rejectedPromise<ReadResult>(errored.addRef(js));
}
KJ_CASE_ONEOF(readable, Readable) {
// TODO(conform): Requiring serialized read requests is non-conformant, but we've never had a
// use case for them. At one time, our implementation of TransformStream supported multiple
// simultaneous read requests, but it is highly unlikely that anyone relied on this. Our
// ReadableStream implementation that wraps native streams has never supported them, our
// TransformStream implementation is primarily (only?) used for constructing manually
// streamed Responses, and no teed ReadableStream has ever supported them.
if (readPending) {
return js.rejectedPromise<ReadResult>(
js.v8TypeError(
"This ReadableStream only supports a single pending read request at a time."_kj));
}
readPending = true;
// TODO(now): This is the implementation we should be able to move to except there's a bug
// somewhere in the awaitIo implementation that allows IdentityTransformStream to hang.
auto promise = kj::evalNow([&] {
return readable->tryRead(bytes.begin(), atLeast, bytes.size());
});
KJ_IF_MAYBE(readerLock, readState.tryGet<ReaderLocked>()) {
promise = KJ_ASSERT_NONNULL(readerLock->getCanceler())->wrap(kj::mv(promise));
}
// TODO(soon): We use awaitIoLegacy() here because if the stream terminates in JavaScript in
// this same isolate, then the promise may actually be waiting on JavaScript to do something,
// and so should not be considered waiting on external I/O. We will need to use
// registerPendingEvent() manually when reading from an external stream. Ideally, we would
// refactor the implementation so that when waiting on a JavaScript stream, we strictly use
// jsg::Promises and not kj::Promises, so that it doesn't look like I/O at all, and there's
// no need to drop the isolate lock and take it again every time some data is read/written.
// That's a larger refactor, though.
return IoContext::current().awaitIoLegacy(kj::mv(promise)).then(js,
[this, store = kj::mv(store), byteOffset, byteLength]
(jsg::Lock& js, size_t amount) mutable -> jsg::Promise<ReadResult> {
readPending = false;
KJ_ASSERT(amount <= byteLength);
if (amount == 0) {
if (!state.is<StreamStates::Errored>()) {
doClose();
}
return js.resolvedPromise(ReadResult { .done = true });
}
// Return a slice so the script can see how many bytes were read.
auto buffer = v8::ArrayBuffer::New(js.v8Isolate, store);
auto ui8Handle = v8::Uint8Array::New(buffer, byteOffset, amount);
return js.resolvedPromise(ReadResult {
.value = js.v8Ref(ui8Handle.As<v8::Value>()),
.done = false
});
}, [this](jsg::Lock& js, jsg::Value reason) -> jsg::Promise<ReadResult> {
readPending = false;
if (!state.is<StreamStates::Errored>()) {
doError(js, reason.getHandle(js));
}
return js.rejectedPromise<ReadResult>(kj::mv(reason));
});
}
}
KJ_UNREACHABLE;
}
jsg::Promise<void> ReadableStreamInternalController::pipeTo(
jsg::Lock& js,
WritableStreamController& destination,
PipeToOptions options) {
KJ_DASSERT(!isLockedToReader());
KJ_DASSERT(!destination.isLockedToWriter());
disturbed = true;
KJ_IF_MAYBE(promise, destination.tryPipeFrom(js,
KJ_ASSERT_NONNULL(owner).addRef(),
kj::mv(options))) {
return kj::mv(*promise);
}
return js.rejectedPromise<void>(
js.v8TypeError("This ReadableStream cannot be piped to this WritableStream."_kj));
}
jsg::Promise<void> ReadableStreamInternalController::cancel(
jsg::Lock& js,
jsg::Optional<v8::Local<v8::Value>> maybeReason) {
disturbed = true;
KJ_IF_MAYBE(errored, state.tryGet<StreamStates::Errored>()) {
return js.rejectedPromise<void>(errored->getHandle(js));
}
doCancel(js, maybeReason);
return js.resolvedPromise();
}
void ReadableStreamInternalController::doCancel(
jsg::Lock& js,
jsg::Optional<v8::Local<v8::Value>> maybeReason) {
auto exception = reasonToException(js, maybeReason);
KJ_IF_MAYBE(locked, readState.tryGet<ReaderLocked>()) {
KJ_ASSERT_NONNULL(locked->getCanceler())->cancel(kj::cp(exception));
}
KJ_IF_MAYBE(readable, state.tryGet<Readable>()) {
(*readable)->cancel(kj::mv(exception));
doClose();
}
}
void ReadableStreamInternalController::doClose() {
state.init<StreamStates::Closed>();
KJ_IF_MAYBE(locked, readState.tryGet<ReaderLocked>()) {
maybeResolvePromise(locked->getClosedFulfiller());
} else KJ_IF_MAYBE(locked, readState.tryGet<PipeLocked>()) {
readState.init<Unlocked>();
}
}
void ReadableStreamInternalController::doError(jsg::Lock& js, v8::Local<v8::Value> reason) {
state.init<StreamStates::Errored>(js.v8Ref(reason));
KJ_IF_MAYBE(locked, readState.tryGet<ReaderLocked>()) {
maybeRejectPromise<void>(locked->getClosedFulfiller(), reason);
} else KJ_IF_MAYBE(locked, readState.tryGet<PipeLocked>()) {
readState.init<Unlocked>();
}
}
ReadableStreamController::Tee ReadableStreamInternalController::tee(jsg::Lock& js) {
JSG_REQUIRE(!isLockedToReader(), TypeError,
"This ReadableStream is currently locked to a reader.");
readState.init<Locked>();
disturbed = true;
KJ_SWITCH_ONEOF(state) {
KJ_CASE_ONEOF(closed, StreamStates::Closed) {
// Create two closed ReadableStreams.
return Tee {
.branch1 =
jsg::alloc<ReadableStream>(ReadableStreamInternalController(closed)),
.branch2 =
jsg::alloc<ReadableStream>(ReadableStreamInternalController(closed)),
};
}
KJ_CASE_ONEOF(errored, StreamStates::Errored) {
// Create two errored ReadableStreams.
return Tee {
.branch1 =
jsg::alloc<ReadableStream>(ReadableStreamInternalController(errored.addRef(js))),
.branch2 =
jsg::alloc<ReadableStream>(ReadableStreamInternalController(errored.addRef(js))),
};
}
KJ_CASE_ONEOF(readable, Readable) {
auto& ioContext = IoContext::current();
auto makeTee =
[&](kj::Own<ReadableStreamSource> b1, kj::Own<ReadableStreamSource> b2) -> Tee {
doClose();
if (ioContext.isInspectorEnabled()) {
b1 = kj::heap<WarnIfUnusedStream>(kj::mv(b1), ioContext);
b2 = kj::heap<WarnIfUnusedStream>(kj::mv(b2), ioContext);
}
return Tee {
.branch1 = jsg::alloc<ReadableStream>(ioContext, kj::mv(b1)),
.branch2 = jsg::alloc<ReadableStream>(ioContext, kj::mv(b2)),
};
};
auto bufferLimit = ioContext.getLimitEnforcer().getBufferingLimit();
KJ_IF_MAYBE(tee, readable->tryTee(bufferLimit)) {
// This ReadableStreamSource has an optimized tee implementation.
return makeTee(kj::mv(tee->branches[0]), kj::mv(tee->branches[1]));
}
auto tee = kj::newTee(kj::heap<TeeAdapter>(kj::mv(readable)), bufferLimit);
return makeTee(
kj::heap<TeeBranch>(newTeeErrorAdapter(kj::mv(tee.branches[0]))),
kj::heap<TeeBranch>(newTeeErrorAdapter(kj::mv(tee.branches[1]))));
}
}
KJ_UNREACHABLE;
}
kj::Maybe<kj::Own<ReadableStreamSource>> ReadableStreamInternalController::removeSource(
jsg::Lock& js) {
JSG_REQUIRE(!isLockedToReader(), TypeError,
"This ReadableStream is currently locked to a reader.");
JSG_REQUIRE(!disturbed, TypeError, "This ReadableStream is disturbed.");
readState.init<Locked>();
disturbed = true;
KJ_SWITCH_ONEOF(state) {
KJ_CASE_ONEOF(closed, StreamStates::Closed) {
class NullSource final: public ReadableStreamSource {
public:
kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
return size_t(0);
}
kj::Maybe<uint64_t> tryGetLength(StreamEncoding encoding) override {
return uint64_t(0);
}
};
return kj::heap<NullSource>();
}
KJ_CASE_ONEOF(errored, StreamStates::Errored) {
kj::throwFatalException(js.exceptionToKj(errored.addRef(js)));
}
KJ_CASE_ONEOF(readable, Readable) {
auto result = kj::mv(readable);
state.init<StreamStates::Closed>();
return kj::Maybe<kj::Own<ReadableStreamSource>>(kj::mv(result));
}
}
KJ_UNREACHABLE;
}
bool ReadableStreamInternalController::lockReader(jsg::Lock& js, Reader& reader) {
if (isLockedToReader()) {
return false;
}
auto prp = js.newPromiseAndResolver<void>();
prp.promise.markAsHandled();
auto lock = ReaderLocked(reader, kj::mv(prp.resolver),
IoContext::current().addObject(kj::heap<kj::Canceler>()));
KJ_SWITCH_ONEOF(state) {
KJ_CASE_ONEOF(closed, StreamStates::Closed) {
maybeResolvePromise(lock.getClosedFulfiller());
}
KJ_CASE_ONEOF(errored, StreamStates::Errored) {
maybeRejectPromise<void>(lock.getClosedFulfiller(), errored.getHandle(js));
}
KJ_CASE_ONEOF(readable, Readable) {
// Nothing to do.
}
}
readState = kj::mv(lock);
reader.attach(*this, kj::mv(prp.promise));
return true;
}
void ReadableStreamInternalController::releaseReader(
Reader& reader,
kj::Maybe<jsg::Lock&> maybeJs) {
KJ_IF_MAYBE(locked, readState.tryGet<ReaderLocked>()) {
KJ_ASSERT(&locked->getReader() == &reader);
KJ_IF_MAYBE(js, maybeJs) {
JSG_REQUIRE(KJ_ASSERT_NONNULL(locked->getCanceler())->isEmpty(), TypeError,
"Cannot call releaseLock() on a reader with outstanding read promises.");
maybeRejectPromise<void>(
locked->getClosedFulfiller(),
js->v8TypeError("This ReadableStream reader has been released."_kj));
}
auto lock = kj::mv(*locked);
// When maybeJs is nullptr, that means releaseReader was called when the reader is
// being deconstructed and not as the result of explicitly calling releaseLock. In
// that case, we don't want to change the lock state itself because we do not have
// an isolate lock. Moving the lock above will free the lock state while keeping the
// ReadableStream marked as locked.
if (maybeJs != nullptr) {
readState.template init<Unlocked>();
}
}
}
WritableStreamInternalController::~WritableStreamInternalController() noexcept(false) {
KJ_IF_MAYBE(locked, writeState.tryGet<WriterLocked>()) {
auto lock = kj::mv(*locked);
writeState.init<Unlocked>();
}
}
jsg::Ref<WritableStream> WritableStreamInternalController::addRef() {
return KJ_ASSERT_NONNULL(owner).addRef();
}
jsg::Promise<void> WritableStreamInternalController::write(
jsg::Lock& js,
jsg::Optional<v8::Local<v8::Value>> value) {
if (isClosedOrClosing()) {
return js.rejectedPromise<void>(
js.v8TypeError("This WritableStream has been closed."_kj));
}
KJ_SWITCH_ONEOF(state) {
KJ_CASE_ONEOF(closed, StreamStates::Closed) {
// Handled by isClosedOrClosing().
KJ_UNREACHABLE;
}
KJ_CASE_ONEOF(errored, StreamStates::Errored) {
return js.rejectedPromise<void>(errored.addRef(js));
}
KJ_CASE_ONEOF(writable, Writable) {
if (value == nullptr) {
return js.resolvedPromise();
}
auto chunk = KJ_ASSERT_NONNULL(value);
std::shared_ptr<v8::BackingStore> store;
size_t byteLength = 0;
size_t byteOffset = 0;
if (chunk->IsArrayBuffer()) {
auto buffer = chunk.As<v8::ArrayBuffer>();
store = buffer->GetBackingStore();
byteLength = buffer->ByteLength();
} else if (chunk->IsArrayBufferView()) {
auto view = chunk.As<v8::ArrayBufferView>();
store = view->Buffer()->GetBackingStore();
byteLength = view->ByteLength();
byteOffset = view->ByteOffset();
} else if (chunk->IsString()) {
// TODO(later): This really ought to return a rejected promise and not a sync throw.
// This case caused me a moment of confusion during testing, so I think it's worth
// a specific error message.
throwTypeErrorAndConsoleWarn(
"This TransformStream is being used as a byte stream, but received a string on its "
"writable side. If you wish to write a string, you'll probably want to explicitly "
"UTF-8-encode it with TextEncoder.");
} else {
// TODO(later): This really ought to return a rejected promise and not a sync throw.
throwTypeErrorAndConsoleWarn(
"This TransformStream is being used as a byte stream, but received an object of "
"non-ArrayBuffer/ArrayBufferView type on its writable side.");
}
if (byteLength == 0) {
return js.resolvedPromise();
}
auto prp = js.newPromiseAndResolver<void>();
queue.push_back(WriteEvent {
.outputLock = IoContext::current().waitForOutputLocksIfNecessaryIoOwn(),
.event = Write {
.promise = kj::mv(prp.resolver),
.ownBytes = store,
.bytes = kj::ArrayPtr<kj::byte>(static_cast<kj::byte*>(store->Data()) + byteOffset,
byteLength),
}
});
ensureWriting(js);
return kj::mv(prp.promise);
}
}
KJ_UNREACHABLE;
}
jsg::Promise<void> WritableStreamInternalController::close(
jsg::Lock& js,
bool markAsHandled) {
if (isClosedOrClosing()) {
auto reason = js.v8TypeError("This WritableStream has been closed."_kj);
return rejectedMaybeHandledPromise<void>(js, reason, markAsHandled);
}
KJ_SWITCH_ONEOF(state) {
KJ_CASE_ONEOF(closed, StreamStates::Closed) {
// Handled by isClosedOrClosing().
KJ_UNREACHABLE;
}
KJ_CASE_ONEOF(errored, StreamStates::Errored) {
auto reason = errored.getHandle(js);
return rejectedMaybeHandledPromise<void>(js, reason, markAsHandled);
}
KJ_CASE_ONEOF(writable, Writable) {
auto prp = js.newPromiseAndResolver<void>();
if (markAsHandled) {
prp.promise.markAsHandled();
}
queue.push_back(WriteEvent {
.outputLock = IoContext::current().waitForOutputLocksIfNecessaryIoOwn(),
.event = Close { .promise = kj::mv(prp.resolver) }
});
ensureWriting(js);
return kj::mv(prp.promise);
}
}
KJ_UNREACHABLE;
}
jsg::Promise<void> WritableStreamInternalController::abort(
jsg::Lock& js,
jsg::Optional<v8::Local<v8::Value>> maybeReason) {
return doAbort(js, maybeReason.orDefault(js.v8Undefined()));
}
jsg::Promise<void> WritableStreamInternalController::doAbort(
jsg::Lock& js,
v8::Local<v8::Value> reason,
AbortOptions options) {
// If maybePendingRejection is set, then the returned abort promise will be rejected
// with the specified error once the abort is completed, otherwise the promise will
// be resolved with undefined.
KJ_IF_MAYBE(writable, state.tryGet<Writable>()) {
auto exception = js.exceptionToKj(js.v8Ref(reason));
if (queue.empty()) {
KJ_ASSERT(maybePendingAbort == nullptr);
(*writable)->abort(kj::cp(exception));
doError(js, reason);
return options.reject ?
rejectedMaybeHandledPromise<void>(js, reason, options.handled) :
js.resolvedPromise();
}
KJ_IF_MAYBE(pendingAbort, maybePendingAbort) {
pendingAbort->reject = options.reject;
return pendingAbort->whenResolved();
}
maybePendingAbort = PendingAbort(js, reason, options.reject);
auto promise = KJ_ASSERT_NONNULL(maybePendingAbort).whenResolved();
if (options.handled) {
promise.markAsHandled();
}
return kj::mv(promise);
}
return options.reject ?
rejectedMaybeHandledPromise<void>(js, reason, options.handled) :
js.resolvedPromise();
}
kj::Maybe<jsg::Promise<void>> WritableStreamInternalController::tryPipeFrom(
jsg::Lock& js,
jsg::Ref<ReadableStream> source,
PipeToOptions options) {
// The ReadableStream source here can be either a JavaScript-backed ReadableStream
// or ReadableStreamSource-backed.
//
// If the source is ReadableStreamSource-backed, then we can use kj's low level mechanisms
// for piping the data. If the source is JavaScript-backed, then we need to rely on the
// JavaScript-based Promise API for piping the data.
auto preventAbort = options.preventAbort.orDefault(false);
auto preventClose = options.preventClose.orDefault(false);
auto preventCancel = options.preventCancel.orDefault(false);
auto pipeThrough = options.pipeThrough;
// If a signal is provided, we need to check that it is not already triggered. If it
// is, we return a rejected promise using the signal's reason.
KJ_IF_MAYBE(signal, options.signal) {
if ((*signal)->getAborted()) {
return rejectedMaybeHandledPromise<void>(js, (*signal)->getReason(js), pipeThrough);
}
}
// With either type of source, our first step is to acquire the source pipe lock. This
// will help abstract most of the details of which type of source we're working with.
auto& sourceLock =
KJ_ASSERT_NONNULL(source->getController().tryPipeLock(KJ_ASSERT_NONNULL(owner).addRef()));
// Let's also acquire the destination pipe lock.
writeState = PipeLocked{ kj::mv(source) };
// If the source has errored, the spec requires us to reject the pipe promise and, if preventAbort
// is false, error the destination (Propagate error forward). The errored source will be unlocked
// immediately. The destination will be unlocked once the abort completes.
KJ_IF_MAYBE(errored, sourceLock.tryGetErrored(js)) {
sourceLock.release(js);
if (!preventAbort) {
KJ_IF_MAYBE(writable, state.tryGet<Writable>()) {
return doAbort(js, *errored, { .reject = true, .handled = pipeThrough });
}
}
// If preventAbort was true, we're going to unlock the destination now.
writeState.init<Unlocked>();
return rejectedMaybeHandledPromise<void>(js, *errored, pipeThrough);
}
// If the destination has errored, the spec requires us to reject the pipe promise and, if
// preventCancel is false, error the source (Propagate error backward). The errored destination
// will be unlocked immediately.
KJ_IF_MAYBE(errored, state.tryGet<StreamStates::Errored>()) {
writeState.init<Unlocked>();
if (!preventCancel) {
sourceLock.release(js, errored->getHandle(js));
} else {
sourceLock.release(js);
}
return rejectedMaybeHandledPromise<void>(js, errored->getHandle(js), pipeThrough);
}
// If the source has closed, the spec requires us to close the destination if preventClose
// is false (Propagate closing forward). The source is unlocked immediately. The destination
// will be unlocked as soon as the close completes.
if (sourceLock.isClosed()) {
sourceLock.release(js);
if (!preventClose) {
// The spec would have us check to see if `destination` is errored and, if so, return its
// stored error. But if `destination` were errored, we would already have caught that case
// above. The spec is probably concerned about cases where the readable and writable sides
// transition to such states in a racey way. But our pump implementation will take care of
// this naively.
KJ_ASSERT(!state.is<StreamStates::Errored>());
if (!isClosedOrClosing()) {
return close(js);
}
}
writeState.init<Unlocked>();
return js.resolvedPromise();
}
// If the destination has closed, the spec requires us to close the source if
// preventCancel is false (Propagate closing backward).
if (isClosedOrClosing()) {
auto destClosed = js.v8TypeError("This destination writable stream is closed."_kj);
writeState.init<Unlocked>();
if (!preventCancel) {
sourceLock.release(js, destClosed);
} else {
sourceLock.release(js);
}
return rejectedMaybeHandledPromise<void>(js, destClosed, pipeThrough);
}
// The pipe will continue until either the source closes or errors, or until the destination
// closes or errors. In either case, both will end up being closed or errored, which will
// release the locks on both.
//
// For either type of source, our next step is to wait for the write loop to process the
// pending Pipe event we queue below.
auto prp = js.newPromiseAndResolver<void>();
if (pipeThrough) {
prp.promise.markAsHandled();
}
queue.push_back(WriteEvent {
.outputLock = IoContext::current().waitForOutputLocksIfNecessaryIoOwn(),
.event = Pipe {
.parent = *this,
.source = sourceLock,
.promise = kj::mv(prp.resolver),
.preventAbort = preventAbort,
.preventClose = preventClose,
.preventCancel = preventCancel,
.maybeSignal = kj::mv(options.signal)
},
});
ensureWriting(js);
return kj::mv(prp.promise);
}
kj::Maybe<kj::Own<WritableStreamSink>> WritableStreamInternalController::removeSink(
jsg::Lock& js) {
JSG_REQUIRE(!isLockedToWriter(), TypeError,
"This WritableStream is currently locked to a writer.");
JSG_REQUIRE(!isClosedOrClosing(), TypeError, "This WritableStream is closed.");
writeState.init<Locked>();
KJ_SWITCH_ONEOF(state) {
KJ_CASE_ONEOF(closed, StreamStates::Closed) {
// Handled by the isClosedOrClosing() check above;
KJ_UNREACHABLE;
}
KJ_CASE_ONEOF(errored, StreamStates::Errored) {
kj::throwFatalException(js.exceptionToKj(errored.addRef(js)));
}
KJ_CASE_ONEOF(writable, Writable) {
auto result = kj::mv(writable);
state.init<StreamStates::Closed>();
return kj::Maybe<kj::Own<WritableStreamSink>>(kj::mv(result));
}
}
KJ_UNREACHABLE;
}
kj::Maybe<int> WritableStreamInternalController::getDesiredSize() {
KJ_SWITCH_ONEOF(state) {