-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathBlob.zig
More file actions
5024 lines (4413 loc) · 186 KB
/
Blob.zig
File metadata and controls
5024 lines (4413 loc) · 186 KB
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
//! The JS `Blob` class can be backed by different forms (in Blob.Store), which
//! represent different sources of Blob. For example, `Bun.file()` returns Blob
//! objects that reference the filesystem (Blob.Store.File). This is how
//! operations like writing `Store.File` to another `Store.File` knows to use a
//! basic file copy instead of a naive read write loop.
const Blob = @This();
const debug = Output.scoped(.Blob, .visible);
pub const Store = @import("./blob/Store.zig");
pub const read_file = @import("./blob/read_file.zig");
pub const write_file = @import("./blob/write_file.zig");
pub const copy_file = @import("./blob/copy_file.zig");
pub fn new(blob: Blob) *Blob {
const result = bun.new(Blob, blob);
result.#ref_count = .init(1);
return result;
}
pub const js = jsc.Codegen.JSBlob;
pub const fromJS = js.fromJS;
pub const fromJSDirect = js.fromJSDirect;
reported_estimated_size: usize = 0,
size: SizeType = 0,
offset: SizeType = 0,
store: ?*Store = null,
content_type: string = "",
content_type_allocated: bool = false,
content_type_was_set: bool = false,
/// JavaScriptCore strings are either latin1 or UTF-16
/// When UTF-16, they're nearly always due to non-ascii characters
charset: strings.AsciiStatus = .unknown,
/// Was it created via file constructor?
is_jsdom_file: bool = false,
/// Reference count, for use with `bun.ptr.ExternalShared`. If the reference count is 0, that means
/// this blob is *not* heap-allocated, and will not be freed in `deinit`.
#ref_count: bun.ptr.RawRefCount(u32, .single_threaded) = .init(0),
globalThis: *JSGlobalObject = undefined,
last_modified: f64 = 0.0,
/// Blob name will lazy initialize when getName is called, but
/// we must be able to set the name, and we need to keep the value alive
/// https://github.com/oven-sh/bun/issues/10178
name: bun.String = .dead,
pub const Ref = bun.ptr.ExternalShared(Blob);
/// Max int of double precision
/// ~4.5 petabytes is probably enough for awhile
/// We want to avoid coercing to a BigInt because that's a heap allocation
/// and it's generally just harder to use
pub const SizeType = u52;
pub const max_size = std.math.maxInt(SizeType);
/// 1: Initial
/// 2: Added byte for whether it's a dom file, length and bytes for `stored_name`,
/// and f64 for `last_modified`. Removed reserved bytes, it's handled by version
/// number.
/// 3: Added File name serialization for File objects (when is_jsdom_file is true)
const serialization_version: u8 = 3;
comptime {
_ = Bun__Blob__getSizeForBindings;
}
pub const ClosingState = enum(u8) {
running,
closing,
};
pub fn getFormDataEncoding(this: *Blob) ?*bun.FormData.AsyncFormData {
var content_type_slice: ZigString.Slice = this.getContentType() orelse return null;
defer content_type_slice.deinit();
const encoding = bun.FormData.Encoding.get(content_type_slice.slice()) orelse return null;
return bun.handleOom(bun.FormData.AsyncFormData.init(bun.default_allocator, encoding));
}
pub fn hasContentTypeFromUser(this: *const Blob) bool {
return this.content_type_was_set or (this.store != null and (this.store.?.data == .file or this.store.?.data == .s3));
}
pub fn contentTypeOrMimeType(this: *const Blob) ?[]const u8 {
if (this.content_type.len > 0) {
return this.content_type;
}
if (this.store) |store| {
switch (store.data) {
.file => |file| {
return file.mime_type.value;
},
.s3 => |s3| {
return s3.mime_type.value;
},
else => return null,
}
}
return null;
}
pub fn isBunFile(this: *const Blob) bool {
const store = this.store orelse return false;
return store.data == .file;
}
pub fn doReadFromS3(this: *Blob, comptime Function: anytype, global: *JSGlobalObject) bun.JSTerminated!JSValue {
debug("doReadFromS3", .{});
const WrappedFn = struct {
pub fn wrapped(b: *Blob, g: *JSGlobalObject, by: []u8) jsc.JSValue {
return jsc.toJSHostCall(g, @src(), Function, .{ b, g, by, .clone });
}
};
return S3BlobDownloadTask.init(global, this, WrappedFn.wrapped);
}
pub fn doReadFile(this: *Blob, comptime Function: anytype, global: *JSGlobalObject) JSValue {
debug("doReadFile", .{});
const Handler = NewReadFileHandler(Function);
var handler = bun.new(Handler, .{
.context = this.*,
.globalThis = global,
});
if (Environment.isWindows) {
var promise = JSPromise.create(global);
const promise_value = promise.toJS();
promise_value.ensureStillAlive();
handler.promise.strong.set(global, promise_value);
read_file.ReadFileUV.start(handler.globalThis.bunVM().eventLoop(), this.store.?, this.offset, this.size, Handler, handler);
return promise_value;
}
const file_read = read_file.ReadFile.create(
bun.default_allocator,
this.store.?,
this.offset,
this.size,
*Handler,
handler,
Handler.run,
) catch |err| bun.handleOom(err);
var read_file_task = read_file.ReadFileTask.createOnJSThread(bun.default_allocator, global, file_read);
// Create the Promise only after the store has been ref()'d.
// The garbage collector runs on memory allocations
// The JSPromise is the next GC'd memory allocation.
// This shouldn't really fix anything, but it's a little safer.
var promise = JSPromise.create(global);
const promise_value = promise.toJS();
promise_value.ensureStillAlive();
handler.promise.strong.set(global, promise_value);
read_file_task.schedule();
debug("doReadFile: read_file_task scheduled", .{});
return promise_value;
}
pub fn NewInternalReadFileHandler(comptime Context: type, comptime Function: anytype) type {
return struct {
pub fn run(handler: *anyopaque, bytes: read_file.ReadFileResultType) void {
Function(bun.cast(Context, handler), bytes);
}
};
}
pub fn doReadFileInternal(this: *Blob, comptime Handler: type, ctx: Handler, comptime Function: anytype, global: *JSGlobalObject) void {
if (Environment.isWindows) {
const ReadFileHandler = NewInternalReadFileHandler(Handler, Function);
return read_file.ReadFileUV.start(global.bunVM().eventLoop(), this.store.?, this.offset, this.size, ReadFileHandler, ctx);
}
const file_read = read_file.ReadFile.createWithCtx(
bun.default_allocator,
this.store.?,
ctx,
NewInternalReadFileHandler(Handler, Function).run,
this.offset,
this.size,
) catch |err| bun.handleOom(err);
var read_file_task = read_file.ReadFileTask.createOnJSThread(bun.default_allocator, global, file_read);
read_file_task.schedule();
}
const FormDataContext = struct {
allocator: std.mem.Allocator,
joiner: StringJoiner,
boundary: []const u8,
failed: bool = false,
globalThis: *jsc.JSGlobalObject,
pub fn onEntry(this: *FormDataContext, name: ZigString, entry: jsc.DOMFormData.FormDataEntry) void {
if (this.failed) return;
var globalThis = this.globalThis;
const allocator = this.allocator;
const joiner = &this.joiner;
const boundary = this.boundary;
joiner.pushStatic("--");
joiner.pushStatic(boundary); // note: "static" here means "outlives the joiner"
joiner.pushStatic("\r\n");
joiner.pushStatic("Content-Disposition: form-data; name=\"");
const name_slice = name.toSlice(allocator);
joiner.push(name_slice.slice(), name_slice.allocator.get());
switch (entry) {
.string => |value| {
joiner.pushStatic("\"\r\n\r\n");
const value_slice = value.toSlice(allocator);
joiner.push(value_slice.slice(), value_slice.allocator.get());
},
.file => |value| {
joiner.pushStatic("\"; filename=\"");
const filename_slice = value.filename.toSlice(allocator);
joiner.push(filename_slice.slice(), filename_slice.allocator.get());
joiner.pushStatic("\"\r\n");
const blob = value.blob;
const content_type = if (blob.content_type.len > 0) blob.content_type else "application/octet-stream";
joiner.pushStatic("Content-Type: ");
joiner.pushStatic(content_type);
joiner.pushStatic("\r\n\r\n");
if (blob.store) |store| {
if (blob.size == Blob.max_size) {
blob.resolveSize();
}
switch (store.data) {
.s3 => |_| {
// TODO: s3
// we need to make this async and use download/downloadSlice
},
.file => |file| {
// TODO: make this async + lazy
const res = jsc.Node.fs.NodeFS.readFile(
globalThis.bunVM().nodeFS(),
.{
.encoding = .buffer,
.path = file.pathlike,
.offset = blob.offset,
.max_size = blob.size,
},
.sync,
);
switch (res) {
.err => |err| {
this.failed = true;
const js_err = err.toJS(globalThis) catch return;
globalThis.throwValue(js_err) catch {};
},
.result => |result| {
joiner.push(result.slice(), result.buffer.allocator);
},
}
},
.bytes => |_| {
joiner.pushStatic(blob.sharedView());
},
}
}
},
}
joiner.pushStatic("\r\n");
}
};
pub fn getContentType(
this: *Blob,
) ?ZigString.Slice {
if (this.content_type.len > 0)
return ZigString.Slice.fromUTF8NeverFree(this.content_type);
return null;
}
const StructuredCloneWriter = struct {
ctx: *anyopaque,
impl: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(jsc.conv) void,
pub const WriteError = error{};
pub fn write(this: StructuredCloneWriter, bytes: []const u8) WriteError!usize {
this.impl(this.ctx, bytes.ptr, @as(u32, @truncate(bytes.len)));
return bytes.len;
}
};
fn _onStructuredCloneSerialize(
this: *Blob,
comptime Writer: type,
writer: Writer,
) !void {
try writer.writeInt(u8, serialization_version, .little);
try writer.writeInt(u64, @intCast(this.offset), .little);
try writer.writeInt(u32, @truncate(this.content_type.len), .little);
try writer.writeAll(this.content_type);
try writer.writeInt(u8, @intFromBool(this.content_type_was_set), .little);
const store_tag: Store.SerializeTag = if (this.store) |store|
if (store.data == .file) .file else .bytes
else
.empty;
try writer.writeInt(u8, @intFromEnum(store_tag), .little);
this.resolveSize();
if (this.store) |store| {
try store.serialize(Writer, writer);
}
try writer.writeInt(u8, @intFromBool(this.is_jsdom_file), .little);
try writeFloat(f64, this.last_modified, Writer, writer);
// Serialize File name if this is a File object
if (this.is_jsdom_file) {
if (this.getNameString()) |name_string| {
const name_slice = name_string.toUTF8(bun.default_allocator);
defer name_slice.deinit();
try writer.writeInt(u32, @truncate(name_slice.slice().len), .little);
try writer.writeAll(name_slice.slice());
} else {
// No name available, write empty string
try writer.writeInt(u32, 0, .little);
}
}
}
pub fn onStructuredCloneSerialize(
this: *Blob,
globalThis: *jsc.JSGlobalObject,
ctx: *anyopaque,
writeBytes: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(jsc.conv) void,
) void {
_ = globalThis;
const Writer = std.Io.GenericWriter(StructuredCloneWriter, StructuredCloneWriter.WriteError, StructuredCloneWriter.write);
const writer = Writer{
.context = .{
.ctx = ctx,
.impl = writeBytes,
},
};
try _onStructuredCloneSerialize(this, Writer, writer);
}
pub fn onStructuredCloneTransfer(
this: *Blob,
globalThis: *jsc.JSGlobalObject,
ctx: *anyopaque,
write: *const fn (*anyopaque, ptr: [*]const u8, len: usize) callconv(.c) void,
) void {
_ = write;
_ = ctx;
_ = this;
_ = globalThis;
}
fn writeFloat(
comptime FloatType: type,
value: FloatType,
comptime Writer: type,
writer: Writer,
) !void {
const bytes: [@sizeOf(FloatType)]u8 = @bitCast(value);
try writer.writeAll(&bytes);
}
fn readFloat(
comptime FloatType: type,
comptime Reader: type,
reader: Reader,
) !FloatType {
var bytes_buf: [@sizeOf(FloatType)]u8 = undefined;
if (Reader == *std.Io.Reader) {
try reader.readSliceAll(&bytes_buf);
} else {
const len = try reader.readAll(&bytes_buf);
if (len < @sizeOf(FloatType)) return error.EndOfStream;
}
return @bitCast(bytes_buf);
}
fn readSlice(
reader: anytype,
len: usize,
allocator: std.mem.Allocator,
) ![]u8 {
var slice = try allocator.alloc(u8, len);
slice = slice[0..try reader.read(slice)];
if (slice.len != len) return error.TooSmall;
return slice;
}
fn _onStructuredCloneDeserialize(
globalThis: *jsc.JSGlobalObject,
comptime Reader: type,
reader: Reader,
) !JSValue {
const allocator = bun.default_allocator;
const version = try reader.readInt(u8, .little);
const offset = try reader.readInt(u64, .little);
const content_type_len = try reader.readInt(u32, .little);
const content_type = try readSlice(reader, content_type_len, allocator);
const content_type_was_set: bool = try reader.readInt(u8, .little) != 0;
const store_tag = try reader.readEnum(Store.SerializeTag, .little);
const blob: *Blob = switch (store_tag) {
.bytes => bytes: {
const bytes_len = try reader.readInt(u32, .little);
const bytes = try readSlice(reader, bytes_len, allocator);
const blob = Blob.init(bytes, allocator, globalThis);
versions: {
if (version == 1) break :versions;
const name_len = try reader.readInt(u32, .little);
const name = try readSlice(reader, name_len, allocator);
if (blob.store) |store| switch (store.data) {
.bytes => |*bytes_store| bytes_store.stored_name = bun.PathString.init(name),
else => {},
};
if (version == 2) break :versions;
}
break :bytes Blob.new(blob);
},
.file => file: {
const pathlike_tag = try reader.readEnum(jsc.Node.PathOrFileDescriptor.SerializeTag, .little);
switch (pathlike_tag) {
.fd => {
const fd = try reader.readStruct(bun.FD);
var path_or_fd = jsc.Node.PathOrFileDescriptor{
.fd = fd,
};
const blob = Blob.new(Blob.findOrCreateFileFromPath(
&path_or_fd,
globalThis,
true,
));
break :file blob;
},
.path => {
const path_len = try reader.readInt(u32, .little);
const path = try readSlice(reader, path_len, default_allocator);
var dest = jsc.Node.PathOrFileDescriptor{
.path = .{
.string = bun.PathString.init(path),
},
};
const blob = Blob.new(Blob.findOrCreateFileFromPath(
&dest,
globalThis,
true,
));
break :file blob;
},
}
return .zero;
},
.empty => Blob.new(Blob.initEmpty(globalThis)),
};
versions: {
if (version == 1) break :versions;
blob.is_jsdom_file = try reader.readInt(u8, .little) != 0;
blob.last_modified = try readFloat(f64, Reader, reader);
if (version == 2) break :versions;
// Version 3: Read File name if this is a File object
if (blob.is_jsdom_file) {
const name_len = try reader.readInt(u32, .little);
const name_bytes = try readSlice(reader, name_len, allocator);
blob.name = bun.String.cloneUTF8(name_bytes);
allocator.free(name_bytes);
}
if (version == 3) break :versions;
}
bun.assertf(blob.isHeapAllocated(), "expected blob to be heap-allocated", .{});
blob.offset = @as(u52, @intCast(offset));
if (content_type.len > 0) {
blob.content_type = content_type;
blob.content_type_allocated = true;
blob.content_type_was_set = content_type_was_set;
}
return blob.toJS(globalThis);
}
pub fn onStructuredCloneDeserialize(globalThis: *jsc.JSGlobalObject, ptr: *[*]u8, end: [*]u8) bun.JSError!JSValue {
const total_length: usize = @intFromPtr(end) - @intFromPtr(ptr.*);
var buffer_stream = std.io.fixedBufferStream(ptr.*[0..total_length]);
const reader = buffer_stream.reader();
const result = _onStructuredCloneDeserialize(globalThis, @TypeOf(reader), reader) catch |err| switch (err) {
error.EndOfStream, error.TooSmall, error.InvalidValue => {
return globalThis.throw("Blob.onStructuredCloneDeserialize failed", .{});
},
error.OutOfMemory => {
return globalThis.throwOutOfMemory();
},
};
// Advance the pointer by the number of bytes consumed
ptr.* = ptr.* + buffer_stream.pos;
return result;
}
const URLSearchParamsConverter = struct {
allocator: std.mem.Allocator,
buf: []u8 = "",
globalThis: *jsc.JSGlobalObject,
pub fn convert(this: *URLSearchParamsConverter, str: ZigString) void {
this.buf = bun.handleOom(str.toOwnedSlice(this.allocator));
}
};
pub fn fromURLSearchParams(
globalThis: *jsc.JSGlobalObject,
allocator: std.mem.Allocator,
search_params: *jsc.URLSearchParams,
) Blob {
var converter = URLSearchParamsConverter{
.allocator = allocator,
.globalThis = globalThis,
};
search_params.toString(URLSearchParamsConverter, &converter, URLSearchParamsConverter.convert);
var store = Blob.Store.init(converter.buf, allocator);
store.mime_type = MimeType.Compact.from(.@"application/x-www-form-urlencoded").toMimeType();
var blob = Blob.initWithStore(store, globalThis);
blob.content_type = store.mime_type.value;
blob.content_type_was_set = true;
return blob;
}
pub fn fromDOMFormData(
globalThis: *jsc.JSGlobalObject,
allocator: std.mem.Allocator,
form_data: *jsc.DOMFormData,
) Blob {
var arena = bun.ArenaAllocator.init(allocator);
defer arena.deinit();
var stack_allocator = std.heap.stackFallback(1024, arena.allocator());
const stack_mem_all = stack_allocator.get();
var hex_buf: [70]u8 = undefined;
const boundary = brk: {
var random = globalThis.bunVM().rareData().nextUUID().bytes;
break :brk std.fmt.bufPrint(&hex_buf, "-WebkitFormBoundary{x}", .{&random}) catch unreachable;
};
var context = FormDataContext{
.allocator = allocator,
.joiner = .{ .allocator = stack_mem_all },
.boundary = boundary,
.globalThis = globalThis,
};
form_data.forEach(FormDataContext, &context, FormDataContext.onEntry);
if (context.failed) {
return Blob.initEmpty(globalThis);
}
context.joiner.pushStatic("--");
context.joiner.pushStatic(boundary);
context.joiner.pushStatic("--\r\n");
const store = Blob.Store.init(bun.handleOom(context.joiner.done(allocator)), allocator);
var blob = Blob.initWithStore(store, globalThis);
blob.content_type = std.fmt.allocPrint(allocator, "multipart/form-data; boundary={s}", .{boundary}) catch |err| bun.handleOom(err);
blob.content_type_allocated = true;
blob.content_type_was_set = true;
return blob;
}
pub fn contentType(this: *const Blob) string {
return this.content_type;
}
pub fn isDetached(this: *const Blob) bool {
return this.store == null;
}
export fn Blob__dupeFromJS(value: jsc.JSValue) ?*Blob {
const this = Blob.fromJS(value) orelse return null;
return Blob__dupe(this);
}
export fn Blob__setAsFile(this: *Blob, path_str: *bun.String) void {
this.is_jsdom_file = true;
// This is not 100% correct...
if (this.store) |store| {
if (store.data == .bytes) {
if (store.data.bytes.stored_name.len == 0) {
const utf8 = path_str.toUTF8Bytes(bun.default_allocator);
store.data.bytes.stored_name = bun.PathString.init(utf8);
}
}
}
}
export fn Blob__dupe(this: *Blob) *Blob {
return new(this.dupeWithContentType(true));
}
export fn Blob__getFileNameString(this: *Blob) callconv(.c) bun.String {
if (this.getFileName()) |filename| {
return bun.String.fromBytes(filename);
}
return bun.String.empty;
}
comptime {
_ = Blob__dupeFromJS;
_ = Blob__dupe;
_ = Blob__setAsFile;
_ = Blob__getFileNameString;
}
pub fn writeFormatForSize(is_jdom_file: bool, size: usize, writer: anytype, comptime enable_ansi_colors: bool) !void {
if (is_jdom_file) {
try writer.writeAll(comptime Output.prettyFmt("<r>File<r>", enable_ansi_colors));
} else {
try writer.writeAll(comptime Output.prettyFmt("<r>Blob<r>", enable_ansi_colors));
}
try writer.print(
comptime Output.prettyFmt(" (<yellow>{f}<r>)", enable_ansi_colors),
.{
bun.fmt.size(size, .{}),
},
);
}
pub fn writeFormat(this: *Blob, comptime Formatter: type, formatter: *Formatter, writer: anytype, comptime enable_ansi_colors: bool) !void {
const Writer = @TypeOf(writer);
if (this.isDetached()) {
if (this.is_jsdom_file) {
try writer.writeAll(comptime Output.prettyFmt("<d>[<r>File<r> detached<d>]<r>", enable_ansi_colors));
} else {
try writer.writeAll(comptime Output.prettyFmt("<d>[<r>Blob<r> detached<d>]<r>", enable_ansi_colors));
}
return;
}
{
const store = this.store.?;
switch (store.data) {
.s3 => |*s3| {
try S3File.writeFormat(s3, Formatter, formatter, writer, enable_ansi_colors, this.content_type, this.offset);
},
.file => |file| {
try writer.writeAll(comptime Output.prettyFmt("<r>FileRef<r>", enable_ansi_colors));
switch (file.pathlike) {
.path => |path| {
try writer.print(
comptime Output.prettyFmt(" (<green>\"{s}\"<r>)<r>", enable_ansi_colors),
.{
path.slice(),
},
);
},
.fd => |fd| {
if (Environment.isWindows) {
switch (fd.decodeWindows()) {
.uv => |uv_file| try writer.print(
comptime Output.prettyFmt(" (<r>fd<d>:<r> <yellow>{d}<r>)<r>", enable_ansi_colors),
.{uv_file},
),
.windows => |handle| {
if (Environment.isDebug) {
@panic("this shouldn't be reachable.");
}
try writer.print(
comptime Output.prettyFmt(" (<r>fd<d>:<r> <yellow>0x{x}<r>)<r>", enable_ansi_colors),
.{@intFromPtr(handle)},
);
},
}
} else {
try writer.print(
comptime Output.prettyFmt(" (<r>fd<d>:<r> <yellow>{d}<r>)<r>", enable_ansi_colors),
.{fd.native()},
);
}
},
}
},
.bytes => {
try writeFormatForSize(this.is_jsdom_file, this.size, writer, enable_ansi_colors);
},
}
}
const show_name = (this.is_jsdom_file and this.getNameString() != null) or (!this.name.isEmpty() and this.store != null and this.store.?.data == .bytes);
if (!this.isS3() and (this.content_type.len > 0 or this.offset > 0 or show_name or this.last_modified != 0.0)) {
try writer.writeAll(" {\n");
{
formatter.indent += 1;
defer formatter.indent -= 1;
if (show_name) {
try formatter.writeIndent(Writer, writer);
try writer.print(
comptime Output.prettyFmt("name<d>:<r> <green>\"{f}\"<r>", enable_ansi_colors),
.{
this.getNameString() orelse bun.String.empty,
},
);
if (this.content_type.len > 0 or this.offset > 0 or this.last_modified != 0) {
try formatter.printComma(Writer, writer, enable_ansi_colors);
}
try writer.writeAll("\n");
}
if (this.content_type.len > 0) {
try formatter.writeIndent(Writer, writer);
try writer.print(
comptime Output.prettyFmt("type<d>:<r> <green>\"{s}\"<r>", enable_ansi_colors),
.{
this.content_type,
},
);
if (this.offset > 0 or this.last_modified != 0) {
try formatter.printComma(Writer, writer, enable_ansi_colors);
}
try writer.writeAll("\n");
}
if (this.offset > 0) {
try formatter.writeIndent(Writer, writer);
try writer.print(
comptime Output.prettyFmt("offset<d>:<r> <yellow>{d}<r>\n", enable_ansi_colors),
.{
this.offset,
},
);
if (this.last_modified != 0) {
try formatter.printComma(Writer, writer, enable_ansi_colors);
}
try writer.writeAll("\n");
}
if (this.last_modified != 0) {
try formatter.writeIndent(Writer, writer);
try writer.print(
comptime Output.prettyFmt("lastModified<d>:<r> <yellow>{d}<r>\n", enable_ansi_colors),
.{
this.last_modified,
},
);
}
}
try formatter.writeIndent(Writer, writer);
try writer.writeAll("}");
}
}
const Retry = enum { @"continue", fail, no };
// TODO: move this to bun.sys?
// we choose not to inline this so that the path buffer is not on the stack unless necessary.
pub noinline fn mkdirIfNotExists(this: anytype, err: bun.sys.Error, path_string: [:0]const u8, err_path: []const u8) Retry {
if (err.getErrno() == .NOENT and this.mkdirp_if_not_exists) {
if (std.fs.path.dirname(path_string)) |dirname| {
var node_fs: jsc.Node.fs.NodeFS = .{};
switch (node_fs.mkdirRecursive(.{
.path = .{ .string = bun.PathString.init(dirname) },
.recursive = true,
.always_return_none = true,
})) {
.result => {
this.mkdirp_if_not_exists = false;
return .@"continue";
},
.err => |err2| {
if (comptime @hasField(@TypeOf(this.*), "errno")) {
this.errno = bun.errnoToZigErr(err2.errno);
}
this.system_error = err.withPath(err_path).toSystemError();
if (comptime @hasField(@TypeOf(this.*), "opened_fd")) {
this.opened_fd = invalid_fd;
}
return .fail;
},
}
}
}
return .no;
}
/// Write an empty string to a file by truncating it.
///
/// This behavior matches what we do with the fast path.
///
/// Returns an encoded `*JSPromise` that resolves if the file
/// - doesn't exist and is created
/// - exists and is truncated
fn writeFileWithEmptySourceToDestination(ctx: *jsc.JSGlobalObject, destination_blob: *Blob, options: WriteFileOptions) bun.JSError!jsc.JSValue {
// SAFETY: null-checked by caller
const destination_store = destination_blob.store.?;
defer destination_blob.detach();
switch (destination_store.data) {
.file => |file| {
// TODO: make this async
const node_fs = ctx.bunVM().nodeFS();
var result = node_fs.truncate(.{
.path = file.pathlike,
.len = 0,
.flags = bun.O.CREAT,
}, .sync);
if (result == .err) {
const errno = result.err.getErrno();
var was_eperm = false;
err: switch (errno) {
// truncate might return EPERM when the parent directory doesn't exist
// #6336
.PERM => {
was_eperm = true;
result.err.errno = @intCast(@intFromEnum(bun.sys.E.NOENT));
continue :err .NOENT;
},
.NOENT => {
if (options.mkdirp_if_not_exists == false) break :err;
// NOTE: if .err is PERM, it ~should~ really is a
// permissions issue
const dirpath: []const u8 = switch (file.pathlike) {
.path => |path| std.fs.path.dirname(path.slice()) orelse break :err,
.fd => {
// NOTE: if this is an fd, it means the file
// exists, so we shouldn't try to mkdir it
// also means PERM is _actually_ a
// permissions issue
if (was_eperm) result.err.errno = @intCast(@intFromEnum(bun.sys.E.PERM));
break :err;
},
};
const mkdir_result = node_fs.mkdirRecursive(.{
.path = .{ .string = bun.PathString.init(dirpath) },
// TODO: Do we really want .mode to be 0o777?
.recursive = true,
.always_return_none = true,
});
if (mkdir_result == .err) {
result.err = mkdir_result.err;
break :err;
}
// SAFETY: we check if `file.pathlike` is an fd or
// not above, returning if it is.
var buf: bun.PathBuffer = undefined;
const mode: bun.Mode = options.mode orelse jsc.Node.fs.default_permission;
while (true) {
const open_res = bun.sys.open(file.pathlike.path.sliceZ(&buf), bun.O.CREAT | bun.O.TRUNC, mode);
switch (open_res) {
// errors fall through and are handled below
.err => |err| {
if (err.getErrno() == .INTR) continue;
result.err = open_res.err;
break :err;
},
.result => |fd| {
fd.close();
return jsc.JSPromise.resolvedPromiseValue(ctx, .jsNumber(0));
},
}
}
},
else => {},
}
result.err = result.err.withPathLike(file.pathlike);
return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, try result.toJS(ctx));
}
},
.s3 => |*s3| {
// create empty file
var aws_options = s3.getCredentialsWithOptions(options.extra_options, ctx) catch |err| {
return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(ctx, ctx.takeException(err));
};
defer aws_options.deinit();
const Wrapper = struct {
promise: jsc.JSPromise.Strong,
store: *Store,
global: *jsc.JSGlobalObject,
pub const new = bun.TrivialNew(@This());
pub fn resolve(result: S3.S3UploadResult, opaque_this: *anyopaque) bun.JSTerminated!void {
const this: *@This() = @ptrCast(@alignCast(opaque_this));
defer this.deinit();
switch (result) {
.success => try this.promise.resolve(this.global, .jsNumber(0)),
.failure => |err| {
try this.promise.reject(this.global, err.toJSWithAsyncStack(this.global, this.store.getPath(), this.promise.get()));
},
}
}
fn deinit(this: *@This()) void {
this.promise.deinit();
this.store.deref();
bun.destroy(this);
}
};
const promise = jsc.JSPromise.Strong.init(ctx);
const promise_value = promise.value();
const proxy = ctx.bunVM().transpiler.env.getHttpProxy(true, null, null);
const proxy_url = if (proxy) |p| p.href else null;
destination_store.ref();
try S3.upload(
&aws_options.credentials,
s3.path(),
"",
destination_blob.contentTypeOrMimeType(),
aws_options.content_disposition,
aws_options.content_encoding,
aws_options.acl,
proxy_url,
aws_options.storage_class,
aws_options.request_payer,
Wrapper.resolve,
Wrapper.new(.{
.promise = promise,
.store = destination_store,
.global = ctx,
}),
);
return promise_value;
},
// Writing to a buffer-backed blob should be a type error,
// making this unreachable. TODO: `{}` -> `unreachable`
.bytes => {},
}
return jsc.JSPromise.resolvedPromiseValue(ctx, jsc.JSValue.jsNumber(0));
}
pub fn writeFileWithSourceDestination(ctx: *jsc.JSGlobalObject, source_blob: *Blob, destination_blob: *Blob, options: WriteFileOptions) bun.JSError!jsc.JSValue {
const destination_store = destination_blob.store orelse Output.panic("Destination blob is detached", .{});
const destination_type = std.meta.activeTag(destination_store.data);
// TODO: make sure this invariant isn't being broken elsewhere (outside