Files
bun.sh/src/bake/DevServer/SerializedFailure.zig
pfg 05d0475c6c Update to zig 0.15.2 (#24204)
Fixes ENG-21287

Build times, from `bun run build && echo '//' >> src/main.zig && time
bun run build`

|Platform|0.14.1|0.15.2|Speedup|
|-|-|-|-|
|macos debug asan|126.90s|106.27s|1.19x|
|macos debug noasan|60.62s|50.85s|1.19x|
|linux debug asan|292.77s|241.45s|1.21x|
|linux debug noasan|146.58s|130.94s|1.12x|
|linux debug use_llvm=false|n/a|78.27s|1.87x|
|windows debug asan|177.13s|142.55s|1.24x|

Runtime performance:

- next build memory usage may have gone up by 5%. Otherwise seems the
same. Some code with writers may have gotten slower, especially one
instance of a counting writer and a few instances of unbuffered writers
that now have vtable overhead.
- File size reduced by 800kb (from 100.2mb to 99.4mb)

Improvements:

- `@export` hack is no longer needed for watch
- native x86_64 backend for linux builds faster. to use it, set use_llvm
false and no_link_obj false. also set `ASAN_OPTIONS=detect_leaks=0`
otherwise it will spam the output with tens of thousands of lines of
debug info errors. may need to use the zig lldb fork for debugging.
- zig test-obj, which we will be able to use for zig unit tests

Still an issue:

- false 'dependency loop' errors remain in watch mode
- watch mode crashes observed

Follow-up:

- [ ] search `comptime Writer: type` and `comptime W: type` and remove
- [ ] remove format_mode in our zig fork
- [ ] remove deprecated.zig autoFormatLabelFallback
- [ ] remove deprecated.zig autoFormatLabel
- [ ] remove deprecated.BufferedWriter and BufferedReader
- [ ] remove override_no_export_cpp_apis as it is no longer needed
- [ ] css Parser(W) -> Parser, and remove all the comptime writer: type
params
- [ ] remove deprecated writer fully

Files that add lines:

```
649     src/deprecated.zig
167     scripts/pack-codegen-for-zig-team.ts
54      scripts/cleartrace-impl.js
46      scripts/cleartrace.ts
43      src/windows.zig
18      src/fs.zig
17      src/bun.js/ConsoleObject.zig
16      src/output.zig
12      src/bun.js/test/debug.zig
12      src/bun.js/node/node_fs.zig
8       src/env_loader.zig
7       src/css/printer.zig
7       src/cli/init_command.zig
7       src/bun.js/node.zig
6       src/string/escapeRegExp.zig
6       src/install/PnpmMatcher.zig
5       src/bun.js/webcore/Blob.zig
4       src/crash_handler.zig
4       src/bun.zig
3       src/install/lockfile/bun.lock.zig
3       src/cli/update_interactive_command.zig
3       src/cli/pack_command.zig
3       build.zig
2       src/Progress.zig
2       src/install/lockfile/lockfile_json_stringify_for_debugging.zig
2       src/css/small_list.zig
2       src/bun.js/webcore/prompt.zig
1       test/internal/ban-words.test.ts
1       test/internal/ban-limits.json
1       src/watcher/WatcherTrace.zig
1       src/transpiler.zig
1       src/shell/builtin/cp.zig
1       src/js_printer.zig
1       src/io/PipeReader.zig
1       src/install/bin.zig
1       src/css/selectors/selector.zig
1       src/cli/run_command.zig
1       src/bun.js/RuntimeTranspilerStore.zig
1       src/bun.js/bindings/JSRef.zig
1       src/bake/DevServer.zig
```

Files that remove lines:

```
-1      src/test/recover.zig
-1      src/sql/postgres/SocketMonitor.zig
-1      src/sql/mysql/MySQLRequestQueue.zig
-1      src/sourcemap/CodeCoverage.zig
-1      src/css/values/color_js.zig
-1      src/compile_target.zig
-1      src/bundler/linker_context/convertStmtsForChunk.zig
-1      src/bundler/bundle_v2.zig
-1      src/bun.js/webcore/blob/read_file.zig
-1      src/ast/base.zig
-2      src/sql/postgres/protocol/ArrayList.zig
-2      src/shell/builtin/mkdir.zig
-2      src/install/PackageManager/patchPackage.zig
-2      src/install/PackageManager/PackageManagerDirectories.zig
-2      src/fmt.zig
-2      src/css/declaration.zig
-2      src/css/css_parser.zig
-2      src/collections/baby_list.zig
-2      src/bun.js/bindings/ZigStackFrame.zig
-2      src/ast/E.zig
-3      src/StandaloneModuleGraph.zig
-3      src/deps/picohttp.zig
-3      src/deps/libuv.zig
-3      src/btjs.zig
-4      src/threading/Futex.zig
-4      src/shell/builtin/touch.zig
-4      src/meta.zig
-4      src/install/lockfile.zig
-4      src/css/selectors/parser.zig
-5      src/shell/interpreter.zig
-5      src/css/error.zig
-5      src/bun.js/web_worker.zig
-5      src/bun.js.zig
-6      src/cli/test_command.zig
-6      src/bun.js/VirtualMachine.zig
-6      src/bun.js/uuid.zig
-6      src/bun.js/bindings/JSValue.zig
-9      src/bun.js/test/pretty_format.zig
-9      src/bun.js/api/BunObject.zig
-14     src/install/install_binding.zig
-14     src/fd.zig
-14     src/bun.js/node/path.zig
-14     scripts/pack-codegen-for-zig-team.sh
-17     src/bun.js/test/diff_format.zig
```

`git diff --numstat origin/main...HEAD | awk '{ print ($1-$2)"\t"$3 }' |
sort -rn`

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
Co-authored-by: Meghan Denny <meghan@bun.com>
Co-authored-by: tayor.fish <contact@taylor.fish>
2025-11-10 14:38:26 -08:00

240 lines
7.9 KiB
Zig

/// Errors sent to the HMR client in the browser are serialized. The same format
/// is used for thrown JavaScript exceptions as well as bundler errors.
/// Serialized failures contain a handle on what file or route they came from,
/// which allows the bundler to dismiss or update stale failures via index as
/// opposed to re-sending a new payload. This also means only changed files are
/// rebuilt, instead of all of the failed files.
///
/// The HMR client in the browser is expected to sort the final list of errors
/// for deterministic output; there is code in DevServer that uses `swapRemove`.
pub const SerializedFailure = @This();
/// Serialized data is always owned by dev.allocator()
/// The first 32 bits of this slice contain the owner
data: []u8,
pub fn deinit(f: SerializedFailure, dev: *DevServer) void {
dev.allocator().free(f.data);
}
/// The metaphorical owner of an incremental file error. The packed variant
/// is given to the HMR runtime as an opaque handle.
pub const Owner = union(enum) {
none,
route: RouteBundle.Index,
client: IncrementalGraph(.client).FileIndex,
server: IncrementalGraph(.server).FileIndex,
pub fn encode(owner: Owner) Packed {
return switch (owner) {
.none => .{ .kind = .none, .data = 0 },
.client => |data| .{ .kind = .client, .data = data.get() },
.server => |data| .{ .kind = .server, .data = data.get() },
.route => |data| .{ .kind = .route, .data = data.get() },
};
}
pub const Packed = packed struct(u32) {
data: u30,
kind: enum(u2) { none, route, client, server },
pub fn decode(owner: Packed) Owner {
return switch (owner.kind) {
.none => .none,
.client => .{ .client = IncrementalGraph(.client).FileIndex.init(owner.data) },
.server => .{ .server = IncrementalGraph(.server).FileIndex.init(owner.data) },
.route => .{ .route = RouteBundle.Index.init(owner.data) },
};
}
comptime {
assert(@as(u32, @bitCast(Packed{ .kind = .none, .data = 1 })) == 1);
}
};
};
pub fn getOwner(failure: SerializedFailure) Owner {
return std.mem.bytesAsValue(Owner.Packed, failure.data[0..4]).decode();
}
/// This assumes the hash map contains only one SerializedFailure per owner.
/// This is okay since SerializedFailure can contain more than one error.
pub const ArrayHashContextViaOwner = struct {
pub fn hash(_: ArrayHashContextViaOwner, k: SerializedFailure) u32 {
return std.hash.int(@as(u32, @bitCast(k.getOwner().encode())));
}
pub fn eql(_: ArrayHashContextViaOwner, a: SerializedFailure, b: SerializedFailure, _: usize) bool {
return @as(u32, @bitCast(a.getOwner().encode())) == @as(u32, @bitCast(b.getOwner().encode()));
}
};
pub const ArrayHashAdapter = struct {
pub fn hash(_: ArrayHashAdapter, own: Owner) u32 {
return std.hash.int(@as(u32, @bitCast(own.encode())));
}
pub fn eql(_: ArrayHashAdapter, a: Owner, b: SerializedFailure, _: usize) bool {
return @as(u32, @bitCast(a.encode())) == @as(u32, @bitCast(b.getOwner().encode()));
}
};
pub const ErrorKind = enum(u8) {
// A log message. The `logger.Kind` is encoded here.
bundler_log_err = 0,
bundler_log_warn = 1,
bundler_log_note = 2,
bundler_log_debug = 3,
bundler_log_verbose = 4,
/// new Error(message)
js_error,
/// new TypeError(message)
js_error_type,
/// new RangeError(message)
js_error_range,
/// Other forms of `Error` objects, including when an error has a
/// `code`, and other fields.
js_error_extra,
/// Non-error with a stack trace
js_primitive_exception,
/// Non-error JS values
js_primitive,
/// new AggregateError(errors, message)
js_aggregate,
};
pub fn initFromJs(dev: *DevServer, owner: Owner, value: JSValue) !SerializedFailure {
{
_ = value;
@panic("TODO");
}
// Avoid small re-allocations without requesting so much from the heap
var sfb = std.heap.stackFallback(65536, dev.allocator());
var payload = std.array_list.Managed(u8).initCapacity(sfb.get(), 65536) catch
unreachable; // enough space
const w = payload.writer();
try w.writeInt(u32, @bitCast(owner.encode()), .little);
// try writeJsValue(value);
// Avoid-recloning if it is was moved to the hap
const data = if (payload.items.ptr == &sfb.buffer)
try dev.allocator().dupe(u8, payload.items)
else
payload.items;
return .{ .data = data };
}
pub fn initFromLog(
dev: *DevServer,
owner: Owner,
// for .client and .server, these are meant to be relative file paths
owner_display_name: []const u8,
messages: []const bun.logger.Msg,
) !SerializedFailure {
assert(messages.len > 0);
// Avoid small re-allocations without requesting so much from the heap
var sfb = std.heap.stackFallback(65536, dev.allocator());
var payload = std.array_list.Managed(u8).initCapacity(sfb.get(), 65536) catch
unreachable; // enough space
const w = payload.writer();
try w.writeInt(u32, @bitCast(owner.encode()), .little);
try writeString32(owner_display_name, w);
try w.writeInt(u32, @intCast(messages.len), .little);
for (messages) |*msg| {
try writeLogMsg(msg, w);
}
// Avoid-recloning if it is was moved to the hap
const data = if (payload.items.ptr == &sfb.buffer)
try dev.allocator().dupe(u8, payload.items)
else
payload.items;
return .{ .data = data };
}
// All "write" functions get a corresponding "read" function in ./client/error.ts
const Writer = std.array_list.Managed(u8).Writer;
fn writeLogMsg(msg: *const bun.logger.Msg, w: Writer) !void {
try w.writeByte(switch (msg.kind) {
inline else => |k| @intFromEnum(@field(ErrorKind, "bundler_log_" ++ @tagName(k))),
});
try writeLogData(msg.data, w);
const notes = msg.notes;
try w.writeInt(u32, @intCast(notes.len), .little);
for (notes) |note| {
try writeLogData(note, w);
}
}
fn writeLogData(data: bun.logger.Data, w: Writer) !void {
try writeString32(data.text, w);
if (data.location) |loc| {
if (loc.line < 0) {
try w.writeInt(u32, 0, .little);
return;
}
assert(loc.column >= 0); // zero based and not negative
try w.writeInt(i32, @intCast(loc.line), .little);
try w.writeInt(u32, @intCast(loc.column), .little);
try w.writeInt(u32, @intCast(loc.length), .little);
// TODO: syntax highlighted line text + give more context lines
try writeString32(loc.line_text orelse "", w);
// The file is not specified here. Since the transpiler runs every file
// in isolation, it would be impossible to reference any other file
// in this Log. Thus, it is not serialized.
} else {
try w.writeInt(u32, 0, .little);
}
}
fn writeString32(data: []const u8, w: Writer) !void {
try w.writeInt(u32, @intCast(data.len), .little);
try w.writeAll(data);
}
// fn writeJsValue(value: JSValue, global: *jsc.JSGlobalObject, w: *Writer) !void {
// if (value.isAggregateError(global)) {
// //
// }
// if (value.jsType() == .DOMWrapper) {
// if (value.as(bun.api.BuildMessage)) |build_error| {
// _ = build_error; // autofix
// //
// } else if (value.as(bun.api.ResolveMessage)) |resolve_error| {
// _ = resolve_error; // autofix
// @panic("TODO");
// }
// }
// _ = w; // autofix
// @panic("TODO");
// }
const std = @import("std");
const bun = @import("bun");
const assert = bun.assert;
const bake = bun.bake;
const Log = bun.logger.Log;
const DevServer = bake.DevServer;
const IncrementalGraph = DevServer.IncrementalGraph;
const RouteBundle = DevServer.RouteBundle;
const jsc = bun.jsc;
const JSValue = jsc.JSValue;