-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
streams.zig
5422 lines (4629 loc) · 187 KB
/
streams.zig
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
const std = @import("std");
const Api = @import("../../api/schema.zig").Api;
const bun = @import("root").bun;
const MimeType = HTTPClient.MimeType;
const ZigURL = @import("../../url.zig").URL;
const HTTPClient = bun.http;
const JSC = bun.JSC;
const js = JSC.C;
const Method = @import("../../http/method.zig").Method;
const FetchHeaders = JSC.FetchHeaders;
const ObjectPool = @import("../../pool.zig").ObjectPool;
const SystemError = JSC.SystemError;
const Output = bun.Output;
const MutableString = bun.MutableString;
const strings = bun.strings;
const string = bun.string;
const default_allocator = bun.default_allocator;
const FeatureFlags = bun.FeatureFlags;
const ArrayBuffer = @import("../base.zig").ArrayBuffer;
const Properties = @import("../base.zig").Properties;
const Async = bun.Async;
const castObj = @import("../base.zig").castObj;
const getAllocator = @import("../base.zig").getAllocator;
const Environment = @import("../../env.zig");
const ZigString = JSC.ZigString;
const IdentityContext = @import("../../identity_context.zig").IdentityContext;
const JSInternalPromise = JSC.JSInternalPromise;
const JSPromise = JSC.JSPromise;
const JSValue = JSC.JSValue;
const JSGlobalObject = JSC.JSGlobalObject;
const E = bun.C.E;
const VirtualMachine = JSC.VirtualMachine;
const Task = JSC.Task;
const JSPrinter = bun.js_printer;
const picohttp = bun.picohttp;
const StringJoiner = bun.StringJoiner;
const uws = bun.uws;
const Blob = JSC.WebCore.Blob;
const Response = JSC.WebCore.Response;
const Request = JSC.WebCore.Request;
const assert = bun.assert;
const Syscall = bun.sys;
const uv = bun.windows.libuv;
const S3MultiPartUpload = @import("../../s3.zig").MultiPartUpload;
const AnyBlob = JSC.WebCore.AnyBlob;
pub const ReadableStream = struct {
value: JSValue,
ptr: Source,
pub const Strong = struct {
held: JSC.Strong = .{},
pub fn globalThis(this: *const Strong) ?*JSGlobalObject {
return this.held.globalThis;
}
pub fn has(this: *Strong) bool {
return this.held.has();
}
pub fn isDisturbed(this: *const Strong, global: *JSC.JSGlobalObject) bool {
if (this.get()) |stream| {
return stream.isDisturbed(global);
}
return false;
}
pub fn init(this: ReadableStream, global: *JSGlobalObject) Strong {
return .{
.held = JSC.Strong.create(this.value, global),
};
}
pub fn get(this: *const Strong) ?ReadableStream {
if (this.held.get()) |value| {
return ReadableStream.fromJS(value, this.held.globalThis.?);
}
return null;
}
pub fn deinit(this: *Strong) void {
// if (this.held.get()) |val| {
// ReadableStream__detach(val, this.held.globalThis.?);
// }
this.held.deinit();
}
pub fn tee(this: *Strong, global: *JSGlobalObject) ?ReadableStream {
if (this.get()) |stream| {
const first, const second = stream.tee(global) orelse return null;
this.held.set(global, first.value);
return second;
}
return null;
}
};
extern fn ReadableStream__tee(stream: JSValue, globalThis: *JSGlobalObject, out1: *JSC.JSValue, out2: *JSC.JSValue) bool;
pub fn tee(this: *const ReadableStream, globalThis: *JSGlobalObject) ?struct { ReadableStream, ReadableStream } {
var out1: JSC.JSValue = .zero;
var out2: JSC.JSValue = .zero;
if (!ReadableStream__tee(this.value, globalThis, &out1, &out2)) {
return null;
}
const out_stream2 = ReadableStream.fromJS(out2, globalThis) orelse return null;
const out_stream1 = ReadableStream.fromJS(out1, globalThis) orelse return null;
return .{ out_stream1, out_stream2 };
}
pub fn toJS(this: *const ReadableStream) JSValue {
return this.value;
}
pub fn reloadTag(this: *ReadableStream, globalThis: *JSC.JSGlobalObject) void {
if (ReadableStream.fromJS(this.value, globalThis)) |stream| {
this.* = stream;
} else {
this.* = .{ .ptr = .{ .Invalid = {} }, .value = .zero };
}
}
pub fn toAnyBlob(
stream: *ReadableStream,
globalThis: *JSC.JSGlobalObject,
) ?JSC.WebCore.AnyBlob {
if (stream.isDisturbed(globalThis)) {
return null;
}
stream.reloadTag(globalThis);
switch (stream.ptr) {
.Blob => |blobby| {
if (blobby.toAnyBlob(globalThis)) |blob| {
stream.done(globalThis);
return blob;
}
},
.File => |blobby| {
if (blobby.lazy == .blob) {
var blob = JSC.WebCore.Blob.initWithStore(blobby.lazy.blob, globalThis);
blob.store.?.ref();
// it should be lazy, file shouldn't have opened yet.
bun.assert(!blobby.started);
stream.done(globalThis);
return AnyBlob{ .Blob = blob };
}
},
.Bytes => |bytes| {
// If we've received the complete body by the time this function is called
// we can avoid streaming it and convert it to a Blob
if (bytes.toAnyBlob()) |blob| {
stream.done(globalThis);
return blob;
}
return null;
},
else => {},
}
return null;
}
pub fn done(this: *const ReadableStream, globalThis: *JSGlobalObject) void {
JSC.markBinding(@src());
// done is called when we are done consuming the stream
// cancel actually mark the stream source as done
// this will resolve any pending promises to done: true
switch (this.ptr) {
.Blob => |source| {
source.parent().cancel();
},
.File => |source| {
source.parent().cancel();
},
.Bytes => |source| {
source.parent().cancel();
},
else => {},
}
this.detachIfPossible(globalThis);
}
pub fn cancel(this: *const ReadableStream, globalThis: *JSGlobalObject) void {
JSC.markBinding(@src());
// cancel the stream
ReadableStream__cancel(this.value, globalThis);
// mark the stream source as done
this.done(globalThis);
}
pub fn abort(this: *const ReadableStream, globalThis: *JSGlobalObject) void {
JSC.markBinding(@src());
// for now we are just calling cancel should be fine
this.cancel(globalThis);
}
pub fn forceDetach(this: *const ReadableStream, globalObject: *JSGlobalObject) void {
ReadableStream__detach(this.value, globalObject);
}
/// Decrement Source ref count and detach the underlying stream if ref count is zero
/// be careful, this can invalidate the stream do not call this multiple times
/// this is meant to be called only once when we are done consuming the stream or from the ReadableStream.Strong.deinit
pub fn detachIfPossible(_: *const ReadableStream, _: *JSGlobalObject) void {
JSC.markBinding(@src());
}
pub const Tag = enum(i32) {
Invalid = -1,
/// ReadableStreamDefaultController or ReadableByteStreamController
JavaScript = 0,
/// ReadableByteStreamController
/// but with a BlobLoader
/// we can skip the BlobLoader and just use the underlying Blob
Blob = 1,
/// ReadableByteStreamController
/// but with a FileLoader
/// we can skip the FileLoader and just use the underlying File
File = 2,
/// This is a direct readable stream
/// That means we can turn it into whatever we want
Direct = 3,
Bytes = 4,
};
pub const Source = union(Tag) {
Invalid: void,
/// ReadableStreamDefaultController or ReadableByteStreamController
JavaScript: void,
/// ReadableByteStreamController
/// but with a BlobLoader
/// we can skip the BlobLoader and just use the underlying Blob
Blob: *ByteBlobLoader,
/// ReadableByteStreamController
/// but with a FileLoader
/// we can skip the FileLoader and just use the underlying File
File: *FileReader,
/// This is a direct readable stream
/// That means we can turn it into whatever we want
Direct: void,
Bytes: *ByteStream,
};
extern fn ReadableStreamTag__tagged(globalObject: *JSGlobalObject, possibleReadableStream: *JSValue, ptr: *?*anyopaque) Tag;
extern fn ReadableStream__isDisturbed(possibleReadableStream: JSValue, globalObject: *JSGlobalObject) bool;
extern fn ReadableStream__isLocked(possibleReadableStream: JSValue, globalObject: *JSGlobalObject) bool;
extern fn ReadableStream__empty(*JSGlobalObject) JSC.JSValue;
extern fn ReadableStream__used(*JSGlobalObject) JSC.JSValue;
extern fn ReadableStream__cancel(stream: JSValue, *JSGlobalObject) void;
extern fn ReadableStream__abort(stream: JSValue, *JSGlobalObject) void;
extern fn ReadableStream__detach(stream: JSValue, *JSGlobalObject) void;
extern fn ReadableStream__fromBlob(
*JSGlobalObject,
store: *anyopaque,
offset: usize,
length: usize,
) JSC.JSValue;
pub fn isDisturbed(this: *const ReadableStream, globalObject: *JSGlobalObject) bool {
JSC.markBinding(@src());
return isDisturbedValue(this.value, globalObject);
}
pub fn isDisturbedValue(value: JSC.JSValue, globalObject: *JSGlobalObject) bool {
JSC.markBinding(@src());
return ReadableStream__isDisturbed(value, globalObject);
}
pub fn isLocked(this: *const ReadableStream, globalObject: *JSGlobalObject) bool {
JSC.markBinding(@src());
return ReadableStream__isLocked(this.value, globalObject);
}
pub fn fromJS(value: JSValue, globalThis: *JSGlobalObject) ?ReadableStream {
JSC.markBinding(@src());
value.ensureStillAlive();
var out = value;
var ptr: ?*anyopaque = null;
return switch (ReadableStreamTag__tagged(globalThis, &out, &ptr)) {
.JavaScript => ReadableStream{
.value = out,
.ptr = .{
.JavaScript = {},
},
},
.Blob => ReadableStream{
.value = out,
.ptr = .{
.Blob = @ptrCast(@alignCast(ptr.?)),
},
},
.File => ReadableStream{
.value = out,
.ptr = .{
.File = @ptrCast(@alignCast(ptr.?)),
},
},
.Bytes => ReadableStream{
.value = out,
.ptr = .{
.Bytes = @ptrCast(@alignCast(ptr.?)),
},
},
// .HTTPRequest => ReadableStream{
// .value = out,
// .ptr = .{
// .HTTPRequest = ptr.asPtr(HTTPRequest),
// },
// },
// .HTTPSRequest => ReadableStream{
// .value = out,
// .ptr = .{
// .HTTPSRequest = ptr.asPtr(HTTPSRequest),
// },
// },
else => null,
};
}
extern fn ZigGlobalObject__createNativeReadableStream(*JSGlobalObject, nativePtr: JSValue) JSValue;
pub fn fromNative(globalThis: *JSGlobalObject, native: JSC.JSValue) JSC.JSValue {
JSC.markBinding(@src());
return ZigGlobalObject__createNativeReadableStream(globalThis, native);
}
pub fn fromBlob(globalThis: *JSGlobalObject, blob: *const Blob, recommended_chunk_size: Blob.SizeType) JSC.JSValue {
JSC.markBinding(@src());
var store = blob.store orelse {
return ReadableStream.empty(globalThis);
};
switch (store.data) {
.bytes => {
var reader = ByteBlobLoader.Source.new(
.{
.globalThis = globalThis,
.context = undefined,
},
);
reader.context.setup(blob, recommended_chunk_size);
return reader.toReadableStream(globalThis);
},
.file => {
var reader = FileReader.Source.new(.{
.globalThis = globalThis,
.context = .{
.event_loop = JSC.EventLoopHandle.init(globalThis.bunVM().eventLoop()),
.start_offset = blob.offset,
.max_size = if (blob.size != Blob.max_size) blob.size else null,
.lazy = .{
.blob = store,
},
},
});
store.ref();
return reader.toReadableStream(globalThis);
},
.s3 => |*s3| {
const credentials = s3.getCredentials();
const path = s3.path();
const proxy = globalThis.bunVM().transpiler.env.getHttpProxy(true, null);
const proxy_url = if (proxy) |p| p.href else null;
return credentials.s3ReadableStream(path, blob.offset, if (blob.size != Blob.max_size) blob.size else null, proxy_url, globalThis);
},
}
}
pub fn fromFileBlobWithOffset(
globalThis: *JSGlobalObject,
blob: *const Blob,
offset: usize,
) bun.JSError!JSC.JSValue {
JSC.markBinding(@src());
var store = blob.store orelse {
return ReadableStream.empty(globalThis);
};
switch (store.data) {
.file => {
var reader = FileReader.Source.new(.{
.globalThis = globalThis,
.context = .{
.event_loop = JSC.EventLoopHandle.init(globalThis.bunVM().eventLoop()),
.start_offset = offset,
.lazy = .{
.blob = store,
},
},
});
store.ref();
return reader.toReadableStream(globalThis);
},
else => {
return globalThis.throw("Expected FileBlob", .{});
},
}
}
pub fn fromPipe(
globalThis: *JSGlobalObject,
parent: anytype,
buffered_reader: anytype,
) JSC.JSValue {
_ = parent; // autofix
JSC.markBinding(@src());
var source = FileReader.Source.new(.{
.globalThis = globalThis,
.context = .{
.event_loop = JSC.EventLoopHandle.init(globalThis.bunVM().eventLoop()),
},
});
source.context.reader.from(buffered_reader, &source.context);
return source.toReadableStream(globalThis);
}
pub fn empty(globalThis: *JSGlobalObject) JSC.JSValue {
JSC.markBinding(@src());
return ReadableStream__empty(globalThis);
}
pub fn used(globalThis: *JSGlobalObject) JSC.JSValue {
JSC.markBinding(@src());
return ReadableStream__used(globalThis);
}
const Base = @import("../../ast/base.zig");
pub const StreamTag = enum(usize) {
invalid = 0,
_,
pub fn init(filedes: bun.FileDescriptor) StreamTag {
var bytes = [8]u8{ 1, 0, 0, 0, 0, 0, 0, 0 };
const filedes_ = @as([8]u8, @bitCast(@as(usize, @as(u56, @truncate(@as(usize, @intCast(filedes)))))));
bytes[1..8].* = filedes_[0..7].*;
return @as(StreamTag, @enumFromInt(@as(u64, @bitCast(bytes))));
}
pub fn fd(this: StreamTag) bun.FileDescriptor {
var bytes = @as([8]u8, @bitCast(@intFromEnum(this)));
if (bytes[0] != 1) {
return bun.invalid_fd;
}
const out: u64 = 0;
@as([8]u8, @bitCast(out))[0..7].* = bytes[1..8].*;
return @as(bun.FileDescriptor, @intCast(out));
}
};
};
pub const StreamStart = union(Tag) {
empty: void,
err: Syscall.Error,
chunk_size: Blob.SizeType,
ArrayBufferSink: struct {
chunk_size: Blob.SizeType,
as_uint8array: bool,
stream: bool,
},
FileSink: FileSinkOptions,
HTTPSResponseSink: void,
HTTPResponseSink: void,
FetchTaskletChunkedRequestSink: void,
ready: void,
owned_and_done: bun.ByteList,
done: bun.ByteList,
pub const FileSinkOptions = struct {
chunk_size: Blob.SizeType = 1024,
input_path: PathOrFileDescriptor,
truncate: bool = true,
close: bool = false,
mode: bun.Mode = 0o664,
pub fn flags(this: *const FileSinkOptions) bun.Mode {
_ = this;
return bun.O.NONBLOCK | bun.O.CLOEXEC | bun.O.CREAT | bun.O.WRONLY;
}
};
pub const Tag = enum {
empty,
err,
chunk_size,
ArrayBufferSink,
FileSink,
HTTPSResponseSink,
HTTPResponseSink,
FetchTaskletChunkedRequestSink,
ready,
owned_and_done,
done,
};
pub fn toJS(this: StreamStart, globalThis: *JSGlobalObject) JSC.JSValue {
switch (this) {
.empty, .ready => {
return .undefined;
},
.chunk_size => |chunk| {
return JSC.JSValue.jsNumber(@as(Blob.SizeType, @intCast(chunk)));
},
.err => |err| {
return globalThis.throwValue(err.toJSC(globalThis)) catch .zero;
},
.owned_and_done => |list| {
return JSC.ArrayBuffer.fromBytes(list.slice(), .Uint8Array).toJS(globalThis, null);
},
.done => |list| {
return JSC.ArrayBuffer.create(globalThis, list.slice(), .Uint8Array);
},
else => {
return .undefined;
},
}
}
pub fn fromJS(globalThis: *JSGlobalObject, value: JSValue) bun.JSError!StreamStart {
if (value.isEmptyOrUndefinedOrNull() or !value.isObject()) {
return .{ .empty = {} };
}
if (value.get(globalThis, "chunkSize")) |chunkSize| {
if (chunkSize.isNumber())
return .{ .chunk_size = @as(Blob.SizeType, @intCast(@as(i52, @truncate(chunkSize.toInt64())))) };
}
return .{ .empty = {} };
}
pub fn fromJSWithTag(
globalThis: *JSGlobalObject,
value: JSValue,
comptime tag: Tag,
) bun.JSError!StreamStart {
if (value.isEmptyOrUndefinedOrNull() or !value.isObject()) {
return .{ .empty = {} };
}
switch (comptime tag) {
.ArrayBufferSink => {
var as_uint8array = false;
var stream = false;
var chunk_size: JSC.WebCore.Blob.SizeType = 0;
var empty = true;
if (value.getOwn(globalThis, "asUint8Array")) |val| {
if (val.isBoolean()) {
as_uint8array = val.toBoolean();
empty = false;
}
}
if (value.fastGet(globalThis, .stream)) |val| {
if (val.isBoolean()) {
stream = val.toBoolean();
empty = false;
}
}
if (value.fastGet(globalThis, .highWaterMark)) |chunkSize| {
if (chunkSize.isNumber()) {
empty = false;
chunk_size = @as(JSC.WebCore.Blob.SizeType, @intCast(@max(0, @as(i51, @truncate(chunkSize.toInt64())))));
}
}
if (!empty) {
return .{
.ArrayBufferSink = .{
.chunk_size = chunk_size,
.as_uint8array = as_uint8array,
.stream = stream,
},
};
}
},
.FileSink => {
var chunk_size: JSC.WebCore.Blob.SizeType = 0;
if (value.fastGet(globalThis, .highWaterMark)) |chunkSize| {
if (chunkSize.isNumber())
chunk_size = @as(JSC.WebCore.Blob.SizeType, @intCast(@max(0, @as(i51, @truncate(chunkSize.toInt64())))));
}
if (value.fastGet(globalThis, .path)) |path| {
if (!path.isString()) {
return .{
.err = Syscall.Error{
.errno = @intFromEnum(bun.C.SystemErrno.EINVAL),
.syscall = .write,
},
};
}
return .{
.FileSink = .{
.chunk_size = chunk_size,
.input_path = .{
.path = path.toSlice(globalThis, globalThis.bunVM().allocator),
},
},
};
} else if (try value.getTruthy(globalThis, "fd")) |fd_value| {
if (!fd_value.isAnyInt()) {
return .{
.err = Syscall.Error{
.errno = @intFromEnum(bun.C.SystemErrno.EBADF),
.syscall = .write,
},
};
}
if (bun.FDImpl.fromJS(fd_value)) |fd| {
return .{
.FileSink = .{
.chunk_size = chunk_size,
.input_path = .{
.fd = fd.encode(),
},
},
};
} else {
return .{
.err = Syscall.Error{
.errno = @intFromEnum(bun.C.SystemErrno.EBADF),
.syscall = .write,
},
};
}
}
return .{
.FileSink = .{
.input_path = .{ .fd = bun.invalid_fd },
.chunk_size = chunk_size,
},
};
},
.FetchTaskletChunkedRequestSink, .HTTPSResponseSink, .HTTPResponseSink => {
var empty = true;
var chunk_size: JSC.WebCore.Blob.SizeType = 2048;
if (value.fastGet(globalThis, .highWaterMark)) |chunkSize| {
if (chunkSize.isNumber()) {
empty = false;
chunk_size = @as(JSC.WebCore.Blob.SizeType, @intCast(@max(256, @as(i51, @truncate(chunkSize.toInt64())))));
}
}
if (!empty) {
return .{
.chunk_size = chunk_size,
};
}
},
else => @compileError("Unuspported tag"),
}
return .{ .empty = {} };
}
};
pub const DrainResult = union(enum) {
owned: struct {
list: std.ArrayList(u8),
size_hint: usize,
},
estimated_size: usize,
empty: void,
aborted: void,
};
pub const StreamResult = union(Tag) {
pending: *Pending,
err: StreamError,
done: void,
owned: bun.ByteList,
owned_and_done: bun.ByteList,
temporary_and_done: bun.ByteList,
temporary: bun.ByteList,
into_array: IntoArray,
into_array_and_done: IntoArray,
pub fn deinit(this: *StreamResult) void {
switch (this.*) {
.owned => |*owned| owned.deinitWithAllocator(bun.default_allocator),
.owned_and_done => |*owned_and_done| owned_and_done.deinitWithAllocator(bun.default_allocator),
.err => |err| {
if (err == .JSValue) {
err.JSValue.unprotect();
}
},
else => {},
}
}
pub const StreamError = union(enum) {
Error: Syscall.Error,
AbortReason: JSC.CommonAbortReason,
// TODO: use an explicit JSC.Strong here.
JSValue: JSC.JSValue,
WeakJSValue: JSC.JSValue,
const WasStrong = enum {
Strong,
Weak,
};
pub fn toJSWeak(this: *const @This(), globalObject: *JSC.JSGlobalObject) struct { JSC.JSValue, WasStrong } {
return switch (this.*) {
.Error => |err| {
return .{ err.toJSC(globalObject), WasStrong.Weak };
},
.JSValue => .{ this.JSValue, WasStrong.Strong },
.WeakJSValue => .{ this.WeakJSValue, WasStrong.Weak },
.AbortReason => |reason| {
const value = reason.toJS(globalObject);
return .{ value, WasStrong.Weak };
},
};
}
};
pub const Tag = enum {
pending,
err,
done,
owned,
owned_and_done,
temporary_and_done,
temporary,
into_array,
into_array_and_done,
};
pub fn slice16(this: *const StreamResult) []const u16 {
const bytes = this.slice();
return @as([*]const u16, @ptrCast(@alignCast(bytes.ptr)))[0..std.mem.bytesAsSlice(u16, bytes).len];
}
pub fn slice(this: *const StreamResult) []const u8 {
return switch (this.*) {
.owned => |owned| owned.slice(),
.owned_and_done => |owned_and_done| owned_and_done.slice(),
.temporary_and_done => |temporary_and_done| temporary_and_done.slice(),
.temporary => |temporary| temporary.slice(),
else => "",
};
}
pub const Writable = union(StreamResult.Tag) {
pending: *Writable.Pending,
err: Syscall.Error,
done: void,
owned: Blob.SizeType,
owned_and_done: Blob.SizeType,
temporary_and_done: Blob.SizeType,
temporary: Blob.SizeType,
into_array: Blob.SizeType,
into_array_and_done: Blob.SizeType,
pub const Pending = struct {
future: Future = .{ .none = {} },
result: Writable,
consumed: Blob.SizeType = 0,
state: StreamResult.Pending.State = .none,
pub fn deinit(this: *@This()) void {
this.future.deinit();
}
pub const Future = union(enum) {
none: void,
promise: JSC.JSPromise.Strong,
handler: Handler,
pub fn deinit(this: *@This()) void {
if (this.* == .promise) {
this.promise.deinit();
this.* = .{ .none = {} };
}
}
};
pub fn promise(this: *Writable.Pending, globalThis: *JSC.JSGlobalObject) *JSPromise {
this.state = .pending;
switch (this.future) {
.promise => |p| {
return p.get();
},
else => {
this.future = .{
.promise = JSC.JSPromise.Strong.init(globalThis),
};
return this.future.promise.get();
},
}
}
pub const Handler = struct {
ctx: *anyopaque,
handler: Fn,
pub const Fn = *const fn (ctx: *anyopaque, result: StreamResult.Writable) void;
pub fn init(this: *Handler, comptime Context: type, ctx: *Context, comptime handler_fn: fn (*Context, StreamResult.Writable) void) void {
this.ctx = ctx;
this.handler = struct {
const handler = handler_fn;
pub fn onHandle(ctx_: *anyopaque, result: StreamResult.Writable) void {
@call(bun.callmod_inline, handler, .{ bun.cast(*Context, ctx_), result });
}
}.onHandle;
}
};
pub fn run(this: *Writable.Pending) void {
if (this.state != .pending) return;
this.state = .used;
switch (this.future) {
.promise => {
var p = this.future.promise;
this.future = .none;
Writable.fulfillPromise(this.result, p.swap(), p.strong.globalThis.?);
},
.handler => |h| {
h.handler(h.ctx, this.result);
},
.none => {},
}
}
};
pub fn isDone(this: *const Writable) bool {
return switch (this.*) {
.owned_and_done, .temporary_and_done, .into_array_and_done, .done, .err => true,
else => false,
};
}
pub fn fulfillPromise(
result: Writable,
promise: *JSPromise,
globalThis: *JSGlobalObject,
) void {
defer promise.asValue(globalThis).unprotect();
switch (result) {
.err => |err| {
promise.reject(globalThis, err.toJSC(globalThis));
},
.done => {
promise.resolve(globalThis, JSValue.jsBoolean(false));
},
else => {
promise.resolve(globalThis, result.toJS(globalThis));
},
}
}
pub fn toJS(this: Writable, globalThis: *JSGlobalObject) JSValue {
return switch (this) {
.err => |err| JSC.JSPromise.rejectedPromise(globalThis, JSValue.c(err.toJS(globalThis))).asValue(globalThis),
.owned => |len| JSC.JSValue.jsNumber(len),
.owned_and_done => |len| JSC.JSValue.jsNumber(len),
.temporary_and_done => |len| JSC.JSValue.jsNumber(len),
.temporary => |len| JSC.JSValue.jsNumber(len),
.into_array => |len| JSC.JSValue.jsNumber(len),
.into_array_and_done => |len| JSC.JSValue.jsNumber(len),
// false == controller.close()
// undefined == noop, but we probably won't send it
.done => JSC.JSValue.jsBoolean(true),
.pending => |pending| pending.promise(globalThis).asValue(globalThis),
};
}
};
pub const IntoArray = struct {
value: JSValue = JSValue.zero,
len: Blob.SizeType = std.math.maxInt(Blob.SizeType),
};
pub const Pending = struct {
future: Future = undefined,
result: StreamResult = .{ .done = {} },
state: State = .none,
pub fn set(this: *Pending, comptime Context: type, ctx: *Context, comptime handler_fn: fn (*Context, StreamResult) void) void {
this.future.init(Context, ctx, handler_fn);
this.state = .pending;
}
pub fn promise(this: *Pending, globalObject: *JSC.JSGlobalObject) *JSC.JSPromise {
const prom = JSC.JSPromise.create(globalObject);
this.future = .{
.promise = .{
.promise = prom,
.globalThis = globalObject,
},
};
this.state = .pending;
return prom;
}
pub const Future = union(enum) {
promise: struct {
promise: *JSPromise,
globalThis: *JSC.JSGlobalObject,
},
handler: Handler,
pub fn init(this: *Future, comptime Context: type, ctx: *Context, comptime handler_fn: fn (*Context, StreamResult) void) void {
this.* = .{
.handler = undefined,
};
this.handler.init(Context, ctx, handler_fn);
}
};
pub const Handler = struct {
ctx: *anyopaque,
handler: Fn,
pub const Fn = *const fn (ctx: *anyopaque, result: StreamResult) void;
pub fn init(this: *Handler, comptime Context: type, ctx: *Context, comptime handler_fn: fn (*Context, StreamResult) void) void {
this.ctx = ctx;
this.handler = struct {
const handler = handler_fn;
pub fn onHandle(ctx_: *anyopaque, result: StreamResult) void {
@call(bun.callmod_inline, handler, .{ bun.cast(*Context, ctx_), result });
}
}.onHandle;
}
};
pub const State = enum {
none,
pending,
used,
};
pub fn run(this: *Pending) void {
if (this.state != .pending) return;
this.state = .used;
switch (this.future) {
.promise => |p| {
StreamResult.fulfillPromise(&this.result, p.promise, p.globalThis);
},
.handler => |h| {
h.handler(h.ctx, this.result);
},
}
}
};
pub fn isDone(this: *const StreamResult) bool {
return switch (this.*) {
.owned_and_done, .temporary_and_done, .into_array_and_done, .done, .err => true,
else => false,
};
}
pub fn fulfillPromise(result: *StreamResult, promise: *JSC.JSPromise, globalThis: *JSC.JSGlobalObject) void {
const vm = globalThis.bunVM();
const loop = vm.eventLoop();
const promise_value = promise.asValue(globalThis);
defer promise_value.unprotect();