const std = @import("std"); const default_download_url = "https://proof.ovh.net/files/100Mb.dat"; const default_upload_url = "https://speed.cloudflare.com/__up"; const default_upload_mb: usize = 100; const Config = struct { download_url: []const u8 = default_download_url, upload_url: []const u8 = default_upload_url, upload_bytes: usize = default_upload_mb * 1024 * 1024, run_download: bool = true, run_upload: bool = true, }; const usage = \\Usage: speediness [options] \\ \\Options: \\ --download-url URL to download from (default: {s}) \\ --upload-url URL to upload to (default: {s}) \\ --upload-mb Megabytes to upload (default: {d}) \\ --both Run both tests \\ --download-only Run the download test only \\ --upload-only Run the upload test only \\ -h, --help Show this help and exit \\ ; fn printUsage() void { std.debug.print(usage, .{ default_download_url, default_upload_url, default_upload_mb }); } fn mbps(bytes: usize, ns: u64) f64 { const secs = @as(f64, @floatFromInt(ns)) / 1e9; if (secs < 0.001) return 0; return (@as(f64, @floatFromInt(bytes)) / secs) / (1024.0 * 1024.0); } fn downloadTest(io: std.Io, allocator: std.mem.Allocator, url: []const u8) !void { var client: std.http.Client = .{ .allocator = allocator, .io = io, }; defer client.deinit(); const uri = try std.Uri.parse(url); var req = try client.request(.GET, uri, .{}); defer req.deinit(); try req.sendBodiless(); var redirect_buffer: [8192]u8 = undefined; var response = try req.receiveHead(&redirect_buffer); if (response.head.status != .ok) { std.debug.print("{}\n", .{response.head.status}); return error.HttpError; } var transfer_buffer: [8192]u8 = undefined; var reader = response.reader(&transfer_buffer); var buf: [131072]u8 = undefined; var total: usize = 0; var iter: usize = 0; const start = std.Io.Timestamp.now(io, .awake); const start_ns: u64 = @intCast(start.nanoseconds); while (true) { const n = reader.readSliceShort(&buf) catch |err| { std.debug.print("\nRead error: {}\n", .{err}); break; }; if (n == 0) break; total += n; iter += 1; if (iter % 8 == 0) { const now_ns: u64 = @intCast(std.Io.Timestamp.now(io, .awake).nanoseconds); const elapsed = now_ns - start_ns; const speed = mbps(total, elapsed); std.debug.print("\r{d:6.1} MB {d:6.2} MB/s {d:6.1} Mbps ", .{ @as(f64, @floatFromInt(total)) / 1e6, speed, speed * 8, }); } } const end_ns: u64 = @intCast(std.Io.Timestamp.now(io, .awake).nanoseconds); const elapsed = end_ns - start_ns; const speed = mbps(total, elapsed); const secs = @as(f64, @floatFromInt(elapsed)) / 1e9; std.debug.print("\n{d:.1} MB in {d:.2}s => {d:.2} MB/s ({d:.1} Mbps)\n", .{ @as(f64, @floatFromInt(total)) / 1e6, secs, speed, speed * 8, }); } fn uploadTest(io: std.Io, allocator: std.mem.Allocator, url: []const u8, upload_bytes: usize) !void { var client: std.http.Client = .{ .allocator = allocator, .io = io, }; defer client.deinit(); const uri = try std.Uri.parse(url); var req = try client.request(.POST, uri, .{ .headers = .{ .content_type = .{ .override = "application/octet-stream" }, }, }); defer req.deinit(); req.transfer_encoding = .{ .content_length = upload_bytes }; var body = try req.sendBodyUnflushed(&.{}); const chunk_size: usize = 131072; const chunk = try allocator.alloc(u8, chunk_size); defer allocator.free(chunk); @memset(chunk, 0x55); var sent: usize = 0; const start = std.Io.Timestamp.now(io, .awake); const start_ns: u64 = @intCast(start.nanoseconds); while (sent < upload_bytes) { const to_send = @min(chunk_size, upload_bytes - sent); try body.writer.writeAll(chunk[0..to_send]); sent += to_send; const now_ns: u64 = @intCast(std.Io.Timestamp.now(io, .awake).nanoseconds); const elapsed = now_ns - start_ns; const speed = mbps(sent, elapsed); std.debug.print("\r {d:6.1} MB {d:6.2} MB/s {d:6.1} Mbps ", .{ @as(f64, @floatFromInt(sent)) / 1e6, speed, speed * 8, }); } try body.end(); if (req.connection) |conn| { try conn.flush(); } const end_ns: u64 = @intCast(std.Io.Timestamp.now(io, .awake).nanoseconds); var redirect_buffer: [8192]u8 = undefined; _ = try req.receiveHead(&redirect_buffer); const elapsed = end_ns - start_ns; const speed = mbps(sent, elapsed); const secs = @as(f64, @floatFromInt(elapsed)) / 1e9; std.debug.print("\n{d:.1} MB in {d:.2}s => {d:.2} MB/s ({d:.1} Mbps)\n", .{ @as(f64, @floatFromInt(sent)) / 1e6, secs, speed, speed * 8, }); } /// Returns the value for an option, taking it either from the rest of the /// current argument after '=' or from the next argument. fn optionValue(args: []const [:0]const u8, i: *usize, eq: ?usize) ![]const u8 { if (eq) |pos| return args[i.*][pos + 1 ..]; if (i.* + 1 >= args.len) { std.debug.print("missing value for '{s}'\n", .{args[i.*]}); return error.MissingValue; } i.* += 1; return args[i.*]; } fn parseArgs(args: []const [:0]const u8) !?Config { // With no arguments, show usage instead of running the tests. if (args.len <= 1) { printUsage(); return null; } var cfg: Config = .{}; // Tracks which of the mutually exclusive mode flags has been seen. var mode: ?[]const u8 = null; var i: usize = 1; while (i < args.len) : (i += 1) { const arg = args[i]; // Split "--flag=value" into name and value position. const eq = std.mem.indexOfScalar(u8, arg, '='); const name = if (eq) |pos| arg[0..pos] else arg; if (std.mem.eql(u8, name, "-h") or std.mem.eql(u8, name, "--help")) { printUsage(); return null; } else if (std.mem.eql(u8, name, "--download-url")) { cfg.download_url = try optionValue(args, &i, eq); } else if (std.mem.eql(u8, name, "--upload-url")) { cfg.upload_url = try optionValue(args, &i, eq); } else if (std.mem.eql(u8, name, "--upload-mb")) { const value = try optionValue(args, &i, eq); const mb = std.fmt.parseInt(usize, value, 10) catch { std.debug.print("invalid --upload-mb value: '{s}'\n", .{value}); return error.InvalidArgument; }; cfg.upload_bytes = mb * 1024 * 1024; } else if (std.mem.eql(u8, name, "--both") or std.mem.eql(u8, name, "--download-only") or std.mem.eql(u8, name, "--upload-only")) { if (mode) |prev| { std.debug.print("{s} and {s} are mutually exclusive\n", .{ prev, name }); return error.InvalidArgument; } mode = name; cfg.run_download = !std.mem.eql(u8, name, "--upload-only"); cfg.run_upload = !std.mem.eql(u8, name, "--download-only"); } else { std.debug.print("unknown argument: '{s}'\n", .{arg}); printUsage(); return error.UnknownArgument; } } return cfg; } pub fn main(init: std.process.Init) !void { const allocator = init.gpa; const args = try init.minimal.args.toSlice(init.arena.allocator()); const cfg = parseArgs(args) catch std.process.exit(2) orelse return; if (cfg.run_download) { downloadTest(init.io, allocator, cfg.download_url) catch |err| { std.debug.print("Download error: {}\n", .{err}); }; } if (cfg.run_upload) { uploadTest(init.io, allocator, cfg.upload_url, cfg.upload_bytes) catch |err| { std.debug.print("Upload error: {}\n", .{err}); }; } }