Files
bun.sh/src/analytics.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

354 lines
12 KiB
Zig

/// Enables analytics. This is used by:
/// - crash_handler.zig's `report` function to anonymously report crashes
///
/// Since this field can be .unknown, it makes more sense to call `isEnabled`
/// instead of processing this field directly.
pub var enabled: enum { yes, no, unknown } = .unknown;
pub var is_ci: enum { yes, no, unknown } = .unknown;
pub fn isEnabled() bool {
return switch (enabled) {
.yes => true,
.no => false,
.unknown => {
enabled = detect: {
if (bun.env_var.DO_NOT_TRACK.get()) {
break :detect .no;
}
if (bun.env_var.HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET.get() != null) {
break :detect .no;
}
break :detect .yes;
};
bun.assert(enabled == .yes or enabled == .no);
return enabled == .yes;
},
};
}
/// This answers, "What parts of bun are people actually using?"
pub const Features = struct {
pub var builtin_modules = std.enums.EnumSet(bun.jsc.ModuleLoader.HardcodedModule).initEmpty();
pub var @"Bun.stderr": usize = 0;
pub var @"Bun.stdin": usize = 0;
pub var @"Bun.stdout": usize = 0;
pub var WebSocket: usize = 0;
pub var abort_signal: usize = 0;
pub var binlinks: usize = 0;
pub var bunfig: usize = 0;
pub var define: usize = 0;
pub var dotenv: usize = 0;
pub var external: usize = 0;
pub var extracted_packages: usize = 0;
pub var fetch: usize = 0;
pub var git_dependencies: usize = 0;
pub var html_rewriter: usize = 0;
/// TCP server from `Bun.listen`
pub var tcp_server: usize = 0;
/// TLS server from `Bun.listen`
pub var tls_server: usize = 0;
pub var http_server: usize = 0;
pub var https_server: usize = 0;
/// Set right before JSC::initialize is called
pub var jsc: usize = 0;
/// Set when bake.DevServer is initialized
pub var dev_server: usize = 0;
pub var lifecycle_scripts: usize = 0;
pub var loaders: usize = 0;
pub var lockfile_migration_from_package_lock: usize = 0;
pub var text_lockfile: usize = 0;
pub var isolated_bun_install: usize = 0;
pub var hoisted_bun_install: usize = 0;
pub var macros: usize = 0;
pub var no_avx2: usize = 0;
pub var no_avx: usize = 0;
pub var shell: usize = 0;
pub var spawn: usize = 0;
pub var standalone_executable: usize = 0;
pub var standalone_shell: usize = 0;
/// Set when invoking a todo panic
pub var todo_panic: usize = 0;
pub var transpiler_cache: usize = 0;
pub var tsconfig: usize = 0;
pub var tsconfig_paths: usize = 0;
pub var virtual_modules: usize = 0;
pub var workers_spawned: usize = 0;
pub var workers_terminated: usize = 0;
pub var napi_module_register: usize = 0;
pub var process_dlopen: usize = 0;
pub var postgres_connections: usize = 0;
pub var s3: usize = 0;
pub var valkey: usize = 0;
pub var csrf_verify: usize = 0;
pub var csrf_generate: usize = 0;
pub var unsupported_uv_function: usize = 0;
pub var exited: usize = 0;
pub var yarn_migration: usize = 0;
pub var pnpm_migration: usize = 0;
pub var yaml_parse: usize = 0;
comptime {
@export(&napi_module_register, .{ .name = "Bun__napi_module_register_count" });
@export(&process_dlopen, .{ .name = "Bun__process_dlopen_count" });
}
pub fn formatter() Formatter {
return Formatter{};
}
pub const Formatter = struct {
pub fn format(_: Formatter, writer: *std.Io.Writer) !void {
const fields = comptime brk: {
const info: std.builtin.Type = @typeInfo(Features);
var buffer: [info.@"struct".decls.len][]const u8 = .{""} ** info.@"struct".decls.len;
var count: usize = 0;
for (info.@"struct".decls) |decl| {
var f = &@field(Features, decl.name);
_ = &f;
const Field = @TypeOf(f);
const FieldT: std.builtin.Type = @typeInfo(Field);
if (FieldT.pointer.child != usize) continue;
buffer[count] = decl.name;
count += 1;
}
break :brk buffer[0..count];
};
var is_first_feature = true;
inline for (fields) |field| {
const count = @field(Features, field);
if (count > 0) {
if (is_first_feature) {
try writer.writeAll("Features: ");
is_first_feature = false;
}
try writer.writeAll(field);
if (count > 1) {
try writer.print("({d}) ", .{count});
} else {
try writer.writeAll(" ");
}
}
}
if (!is_first_feature) {
try writer.writeAll("\n");
}
var builtins = builtin_modules.iterator();
if (builtins.next()) |first| {
try writer.writeAll("Builtins: \"");
try writer.writeAll(@tagName(first));
try writer.writeAll("\" ");
while (builtins.next()) |key| {
try writer.writeAll("\"");
try writer.writeAll(@tagName(key));
try writer.writeAll("\" ");
}
try writer.writeAll("\n");
}
}
};
};
pub fn validateFeatureName(name: []const u8) void {
if (name.len > 64) @compileError("Invalid feature name: " ++ name);
for (name) |char| {
switch (char) {
'a'...'z', 'A'...'Z', '0'...'9', '_', '.', ':', '-' => {},
else => @compileError("Invalid feature name: " ++ name),
}
}
}
pub const packed_features_list = brk: {
const decls = std.meta.declarations(Features);
var names: [decls.len][:0]const u8 = undefined;
var i = 0;
for (decls) |decl| {
if (@TypeOf(@field(Features, decl.name)) == usize) {
validateFeatureName(decl.name);
names[i] = decl.name;
i += 1;
}
}
break :brk names[0..i].*;
};
pub const PackedFeatures = @Type(.{
.@"struct" = .{
.layout = .@"packed",
.backing_integer = u64,
.fields = brk: {
var fields: [64]std.builtin.Type.StructField = undefined;
var i: usize = 0;
for (packed_features_list) |name| {
fields[i] = .{
.name = name,
.type = bool,
.default_value_ptr = &false,
.is_comptime = false,
.alignment = 0,
};
i += 1;
}
while (i < fields.len) : (i += 1) {
fields[i] = .{
.name = std.fmt.comptimePrint("_{d}", .{i}),
.type = bool,
.default_value_ptr = &false,
.is_comptime = false,
.alignment = 0,
};
}
break :brk &fields;
},
.decls = &.{},
.is_tuple = false,
},
});
pub fn packedFeatures() PackedFeatures {
var bits = PackedFeatures{};
inline for (packed_features_list) |name| {
if (@field(Features, name) > 0) {
@field(bits, name) = true;
}
}
return bits;
}
pub const EventName = enum(u8) {
bundle_success,
bundle_fail,
bundle_start,
http_start,
http_build,
};
var random: std.rand.DefaultPrng = undefined;
const platform_arch = if (Environment.isAarch64) analytics.Architecture.arm else analytics.Architecture.x64;
// TODO: move this code somewhere more appropriate, and remove it from "analytics"
// The following code is not currently even used for analytics, just feature-detection
// in order to determine if certain APIs are usable.
pub const GenerateHeader = struct {
pub const GeneratePlatform = struct {
var osversion_name: [32]u8 = undefined;
fn forMac() analytics.Platform {
@memset(&osversion_name, 0);
var platform = analytics.Platform{ .os = analytics.OperatingSystem.macos, .version = &[_]u8{}, .arch = platform_arch };
var len = osversion_name.len - 1;
// this previously used "kern.osrelease", which was the darwin xnu kernel version
// That is less useful than "kern.osproductversion", which is the macOS version
if (std.c.sysctlbyname("kern.osproductversion", &osversion_name, &len, null, 0) == -1) return platform;
platform.version = bun.sliceTo(&osversion_name, 0);
return platform;
}
pub var linux_os_name: std.c.utsname = undefined;
var platform_: analytics.Platform = undefined;
pub const Platform = analytics.Platform;
var linux_kernel_version: Semver.Version = undefined;
var run_once = std.once(struct {
fn run() void {
if (comptime Environment.isMac) {
platform_ = forMac();
} else if (comptime Environment.isPosix) {
platform_ = forLinux();
const release = bun.sliceTo(&linux_os_name.release, 0);
const sliced_string = Semver.SlicedString.init(release, release);
const result = Semver.Version.parse(sliced_string);
linux_kernel_version = result.version.min();
} else if (Environment.isWindows) {
platform_ = Platform{
.os = analytics.OperatingSystem.windows,
.version = &[_]u8{},
.arch = platform_arch,
};
}
}
}.run);
pub fn forOS() analytics.Platform {
run_once.call();
return platform_;
}
// On macOS 13, tests that use sendmsg_x or recvmsg_x hang.
var use_msgx_on_macos_14_or_later: bool = undefined;
var detectUseMsgXOnMacOS14OrLater_once = std.once(detectUseMsgXOnMacOS14OrLater);
fn detectUseMsgXOnMacOS14OrLater() void {
const version = Semver.Version.parseUTF8(forOS().version);
use_msgx_on_macos_14_or_later = version.valid and version.version.max().major >= 14;
}
pub export fn Bun__doesMacOSVersionSupportSendRecvMsgX() i32 {
if (comptime !Environment.isMac) {
// this should not be used on non-mac platforms.
return 0;
}
detectUseMsgXOnMacOS14OrLater_once.call();
return @intFromBool(use_msgx_on_macos_14_or_later);
}
pub fn kernelVersion() Semver.Version {
if (comptime !Environment.isLinux) {
@compileError("This function is only implemented on Linux");
}
_ = forOS();
return linux_kernel_version;
}
export fn Bun__isEpollPwait2SupportedOnLinuxKernel() i32 {
if (comptime !Environment.isLinux) {
return 0;
}
// https://man.archlinux.org/man/epoll_pwait2.2.en#HISTORY
const min_epoll_pwait2 = Semver.Version{
.major = 5,
.minor = 11,
.patch = 0,
};
return switch (kernelVersion().order(min_epoll_pwait2, "", "")) {
.gt => 1,
.eq => 1,
.lt => 0,
};
}
fn forLinux() analytics.Platform {
linux_os_name = std.mem.zeroes(@TypeOf(linux_os_name));
_ = std.c.uname(&linux_os_name);
// Confusingly, the "release" tends to contain the kernel version much more frequently than the "version" field.
const release = bun.sliceTo(&linux_os_name.release, 0);
// Linux DESKTOP-P4LCIEM 5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
if (std.mem.indexOf(u8, release, "microsoft") != null) {
return analytics.Platform{ .os = analytics.OperatingSystem.wsl, .version = release, .arch = platform_arch };
}
return analytics.Platform{ .os = analytics.OperatingSystem.linux, .version = release, .arch = platform_arch };
}
};
};
const std = @import("std");
const analytics = @import("./analytics/schema.zig").analytics;
const bun = @import("bun");
const Environment = bun.Environment;
const Semver = bun.Semver;