diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f17c15c..cf02d62 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,7 +1,7 @@ name: CI/CD with Benchmarks env: - ZIG_VERSION: 0.15.2 + ZIG_VERSION: 0.17.0 on: push: diff --git a/.gitignore b/.gitignore index 1f66876..910837c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .zig-cache/ zig-out/ +zig-pkg/ # Benchmark results benchmark_results.json diff --git a/build.zig b/build.zig index bfbcd80..96fa0ea 100644 --- a/build.zig +++ b/build.zig @@ -39,7 +39,7 @@ pub fn build(b: *std.Build) void { for (zlib_sources) |src| { const src_path = zlib_dep.path(src); - zlib_lib.addCSourceFile(.{ + zlib_lib.root_module.addCSourceFile(.{ .file = src_path, .flags = &[_][]const u8{ "-DHAVE_SYS_TYPES_H", @@ -51,19 +51,30 @@ pub fn build(b: *std.Build) void { }); } - zlib_lib.linkLibC(); + zlib_lib.root_module.link_libc = true; zlib_lib.installHeadersDirectory( zlib_dep.path("."), ".", - .{ .include_extensions = &[_][]const u8{ ".h" } }, + .{ .include_extensions = &[_][]const u8{".h"} }, ); + const zlib_translate_c = b.addTranslateC(.{ + .root_source_file = zlib_dep.path("zlib.h"), + .target = target, + .optimize = optimize, + }); + zlib_translate_c.addIncludePath(zlib_dep.path(".")); + const zlib_mod = zlib_translate_c.createModule(); + // Server module (for internal use and library export) const server_mod = b.addModule("grpc-server", .{ .root_source_file = b.path("src/server.zig"), .target = target, .optimize = optimize, - .imports = &.{.{ .name = "spice", .module = spice_mod }}, + .imports = &.{ + .{ .name = "spice", .module = spice_mod }, + .{ .name = "zlib", .module = zlib_mod }, + }, }); // Client module (for internal use and library export) @@ -71,7 +82,10 @@ pub fn build(b: *std.Build) void { .root_source_file = b.path("src/client.zig"), .target = target, .optimize = optimize, - .imports = &.{.{ .name = "spice", .module = spice_mod }}, + .imports = &.{ + .{ .name = "spice", .module = spice_mod }, + .{ .name = "zlib", .module = zlib_mod }, + }, }); // Benchmark executable @@ -81,10 +95,13 @@ pub fn build(b: *std.Build) void { .root_source_file = b.path("src/benchmark.zig"), .target = target, .optimize = optimize, - .imports = &.{.{ .name = "spice", .module = spice_mod }}, + .imports = &.{ + .{ .name = "spice", .module = spice_mod }, + .{ .name = "zlib", .module = zlib_mod }, + }, }), }); - benchmark.linkLibrary(zlib_lib); + benchmark.root_module.linkLibrary(zlib_lib); b.installArtifact(benchmark); // Benchmark step with automatic server management @@ -95,10 +112,10 @@ pub fn build(b: *std.Build) void { "sh", "-c", "trap 'kill $SERVER_PID 2>/dev/null' EXIT; " ++ - "./zig-out/bin/grpc-server-example & SERVER_PID=$!; " ++ - "sleep 2; " ++ - "./zig-out/bin/grpc-benchmark --host localhost --port 50051 --requests 10 --clients 1 --size 512 --output text; " ++ - "kill $SERVER_PID 2>/dev/null || true", + "./zig-out/bin/grpc-server-example & SERVER_PID=$!; " ++ + "sleep 2; " ++ + "./zig-out/bin/grpc-benchmark --host localhost --port 50051 --requests 10 --clients 1 --size 512 --output text; " ++ + "kill $SERVER_PID 2>/dev/null || true", }); benchmark_cmd.step.dependOn(b.getInstallStep()); benchmark_step.dependOn(&benchmark_cmd.step); @@ -106,9 +123,7 @@ pub fn build(b: *std.Build) void { // Also keep the standalone benchmark executable for manual testing const run_benchmark_manual = b.addRunArtifact(benchmark); run_benchmark_manual.step.dependOn(b.getInstallStep()); - if (b.args) |args| { - run_benchmark_manual.addArgs(args); - } + run_benchmark_manual.addPassthruArgs(); const benchmark_manual_step = b.step("benchmark-manual", "Run benchmark manually (requires server running)"); benchmark_manual_step.dependOn(&run_benchmark_manual.step); @@ -125,7 +140,7 @@ pub fn build(b: *std.Build) void { }, }), }); - server_example.linkLibrary(zlib_lib); + server_example.root_module.linkLibrary(zlib_lib); b.installArtifact(server_example); const client_example = b.addExecutable(.{ @@ -140,7 +155,7 @@ pub fn build(b: *std.Build) void { }, }), }); - client_example.linkLibrary(zlib_lib); + client_example.root_module.linkLibrary(zlib_lib); b.installArtifact(client_example); // Tests @@ -150,10 +165,13 @@ pub fn build(b: *std.Build) void { .root_source_file = b.path("src/tests.zig"), .target = target, .optimize = optimize, - .imports = &.{.{ .name = "spice", .module = spice_mod }}, + .imports = &.{ + .{ .name = "spice", .module = spice_mod }, + .{ .name = "zlib", .module = zlib_mod }, + }, }), }); - tests.linkLibrary(zlib_lib); + tests.root_module.linkLibrary(zlib_lib); const run_tests = b.addRunArtifact(tests); const test_step = b.step("test", "Run tests"); @@ -180,7 +198,7 @@ pub fn build(b: *std.Build) void { }, }), }); - integration_test_server.linkLibrary(zlib_lib); + integration_test_server.root_module.linkLibrary(zlib_lib); const install_integration_test = b.addInstallArtifact(integration_test_server, .{}); const integration_test_step = b.step("integration_test", "Build integration test server"); diff --git a/build.zig.zon b/build.zig.zon index 2a7f0aa..de5938d 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -4,12 +4,12 @@ .fingerprint = 0xbcaa61f2a4ef59ec, .dependencies = .{ .spice = .{ - .url = "https://github.com/judofyr/spice", - .hash = "spice-0.0.0-3FtxfEq9AAASAwEKfAmQ4uDhc9vkuwHrRkjEeEYx1aCP", + .url = "git+https://github.com/judofyr/spice#39186ac9da2b851f558a33926836e605e238694d", + .hash = "spice-0.0.0-3FtxfKu_AADWhWk0I60jjBhn7y-d3K_49oefAeOWwx_S", }, .zlib = .{ .url = "https://github.com/madler/zlib/archive/refs/tags/v1.3.1.tar.gz", - .hash = "1220fed0c74e1019b3ee29edae2051788b080cd96e90d56836eea857b0b966742efb", + .hash = "N-V-__8AAB0eQwD-0MdOEBmz7intriBReIsIDNlukNVoNu6o", }, }, .paths = .{ diff --git a/examples/auth.zig b/examples/auth.zig index 09abf66..589392a 100644 --- a/examples/auth.zig +++ b/examples/auth.zig @@ -1,12 +1,12 @@ const std = @import("std"); const auth = @import("features/auth.zig"); -pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); +pub fn main(init: std.process.Init) !void { + var safe_allocator = std.heap.SafeAllocator.init(init.gpa, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); - var auth_handler = auth.Auth.init(allocator, "my-secret-key"); + var auth_handler = auth.Auth.init(allocator, init.io, "my-secret-key"); // Generate a token const token = try auth_handler.generateToken("user123", 3600); @@ -22,4 +22,4 @@ pub fn main() !void { auth_handler.verifyToken("invalid.token.here") catch |err| { std.debug.print("Expected error: {}\n", .{err}); }; -} \ No newline at end of file +} diff --git a/examples/basic_client.zig b/examples/basic_client.zig index 26f32c2..a8cc9ff 100644 --- a/examples/basic_client.zig +++ b/examples/basic_client.zig @@ -1,12 +1,12 @@ const std = @import("std"); const GrpcClient = @import("grpcclient").GrpcClient; -pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); +pub fn main(init: std.process.Init) !void { + var safe_allocator = std.heap.SafeAllocator.init(init.gpa, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); - var client = try GrpcClient.init(allocator, "localhost", 50051); + var client = try GrpcClient.init(allocator, init.io, "localhost", 50051); defer client.deinit(); // Set authentication diff --git a/examples/basic_server.zig b/examples/basic_server.zig index 2940148..b43d61a 100644 --- a/examples/basic_server.zig +++ b/examples/basic_server.zig @@ -1,12 +1,12 @@ const std = @import("std"); const GrpcServer = @import("grpc").GrpcServer; -pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); +pub fn main(init: std.process.Init) !void { + var safe_allocator = std.heap.SafeAllocator.init(init.gpa, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); - var server = try GrpcServer.init(allocator, 50051, "secret-key"); + var server = try GrpcServer.init(allocator, init.io, 50051, "secret-key"); defer server.deinit(); // Register handlers @@ -30,13 +30,13 @@ pub fn main() !void { try server.start(); } -fn sayHello(request: []const u8, allocator: std.mem.Allocator) ![]u8 { +fn sayHello(request: []const u8, allocator: std.mem.Allocator, _: std.Io) ![]u8 { _ = request; return allocator.dupe(u8, "Hello from gRPC!"); } -fn benchmarkHandler(request: []const u8, allocator: std.mem.Allocator) ![]u8 { +fn benchmarkHandler(request: []const u8, allocator: std.mem.Allocator, io: std.Io) ![]u8 { // Echo the request back with a timestamp for benchmarking - const response = try std.fmt.allocPrint(allocator, "Echo: {s} (processed at {d})", .{ request, std.time.milliTimestamp() }); + const response = try std.fmt.allocPrint(allocator, "Echo: {s} (processed at {d})", .{ request, std.Io.Timestamp.now(io, .real).toMilliseconds() }); return response; } diff --git a/examples/compression.zig b/examples/compression.zig index 8fbff25..48d0e47 100644 --- a/examples/compression.zig +++ b/examples/compression.zig @@ -2,9 +2,9 @@ const std = @import("std"); const compression = @import("features/compression.zig"); pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); + var safe_allocator = std.heap.SafeAllocator.init(init.gpa, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); var comp = compression.Compression.init(allocator); const data = "Hello, this is some test data for compression!"; @@ -26,4 +26,4 @@ pub fn main() !void { std.debug.print("Original size: {}\n", .{data.len}); std.debug.print("Gzip size: {}\n", .{compressed_gzip.len}); std.debug.print("Deflate size: {}\n", .{compressed_deflate.len}); -} \ No newline at end of file +} diff --git a/examples/health.zig b/examples/health.zig index c0ab443..79ccecc 100644 --- a/examples/health.zig +++ b/examples/health.zig @@ -2,9 +2,9 @@ const std = @import("std"); const health = @import("features/health.zig"); pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); + var safe_allocator = std.heap.SafeAllocator.init(init.gpa, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); var health_checker = health.HealthCheck.init(allocator); defer health_checker.deinit(); @@ -25,4 +25,4 @@ pub fn main() !void { health_checker.check("unknown.service") catch |err| { std.debug.print("Expected error for unknown service: {}\n", .{err}); }; -} \ No newline at end of file +} diff --git a/examples/http2_transport.zig b/examples/http2_transport.zig index c50ab4e..caea11d 100644 --- a/examples/http2_transport.zig +++ b/examples/http2_transport.zig @@ -6,9 +6,9 @@ const http2 = struct { }; pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); + var safe_allocator = std.heap.SafeAllocator.init(init.gpa, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); // Create a TCP connection (simplified for example) const stream = try std.net.tcpConnectToHost(allocator, "localhost", 50051); @@ -27,4 +27,4 @@ pub fn main() !void { defer allocator.free(response); std.debug.print("Received: {s}\n", .{response}); -} \ No newline at end of file +} diff --git a/examples/streaming.zig b/examples/streaming.zig index 5da0d0c..217d532 100644 --- a/examples/streaming.zig +++ b/examples/streaming.zig @@ -2,9 +2,9 @@ const std = @import("std"); const streaming = @import("features/streaming.zig"); pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); + var safe_allocator = std.heap.SafeAllocator.init(init.gpa, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); // Create a message stream with buffer size of 5 var stream = streaming.MessageStream.init(allocator, 5); @@ -17,7 +17,7 @@ pub fn main() !void { // Read messages while (stream.pop()) |msg| { - std.debug.print("Message: {s}, End: {}\n", .{msg.data, msg.is_end}); + std.debug.print("Message: {s}, End: {}\n", .{ msg.data, msg.is_end }); allocator.free(msg.data); } -} \ No newline at end of file +} diff --git a/integration_test/test_client.py b/integration_test/test_client.py index f971321..8e9874a 100755 --- a/integration_test/test_client.py +++ b/integration_test/test_client.py @@ -125,46 +125,59 @@ def run_tests(): print("=" * 60) print() - client = SimpleGrpcClient() - # Test 1: Connection print("Test 1: Server Connection") print("-" * 60) + client = SimpleGrpcClient() if not client.connect(): print("\n✗ FAILED: Could not connect to server") print(" Make sure the server is running on localhost:50052") return False + client.close() print() # Test 2: Echo handler print("Test 2: Echo Handler") print("-" * 60) + client = SimpleGrpcClient() + if not client.connect(): + print("✗ FAILED: Echo test failed") + return False test_message = "Hello from Python test client!" if not client.send_message("Echo", test_message): print("✗ FAILED: Echo test failed") client.close() return False + client.close() print() # Test 3: CompressedEcho handler print("Test 3: CompressedEcho Handler") print("-" * 60) + client = SimpleGrpcClient() + if not client.connect(): + print("✗ FAILED: CompressedEcho test failed") + return False if not client.send_message("CompressedEcho", "Test compression"): print("✗ FAILED: CompressedEcho test failed") client.close() return False + client.close() print() # Test 4: HealthCheck handler print("Test 4: HealthCheck Handler") print("-" * 60) + client = SimpleGrpcClient() + if not client.connect(): + print("✗ FAILED: HealthCheck test failed") + return False if not client.send_message("HealthCheck", ""): print("✗ FAILED: HealthCheck test failed") client.close() return False - print() - client.close() + print() print("=" * 60) print("✓ All tests passed!") diff --git a/integration_test/test_server.zig b/integration_test/test_server.zig index cce20d0..379e446 100644 --- a/integration_test/test_server.zig +++ b/integration_test/test_server.zig @@ -3,13 +3,13 @@ const GrpcServer = @import("grpc").GrpcServer; const proto = @import("proto.zig"); const spice = @import("spice"); -pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); +pub fn main(init: std.process.Init) !void { + var safe_allocator = std.heap.SafeAllocator.init(init.gpa, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); const port = 50052; // Use different port to avoid conflicts - var server = try GrpcServer.init(allocator, port, "test-secret-key"); + var server = try GrpcServer.init(allocator, init.io, port, "test-secret-key"); defer server.deinit(); std.log.info("Integration test server starting on port {d}", .{port}); @@ -52,10 +52,10 @@ pub fn main() !void { try server.start(); } -fn echoHandler(request: []const u8, allocator: std.mem.Allocator) ![]u8 { +fn echoHandler(request: []const u8, allocator: std.mem.Allocator, io: std.Io) ![]u8 { // For now, just echo back the request with server info // TODO: Implement proper protobuf decode/encode when Spice API is stable - const timestamp = std.time.timestamp(); + const timestamp = std.Io.Timestamp.now(io, .real).toMilliseconds(); const response = try std.fmt.allocPrint( allocator, "Echo: {s} | Server: gRPC-zig | Time: {d}", @@ -64,9 +64,9 @@ fn echoHandler(request: []const u8, allocator: std.mem.Allocator) ![]u8 { return response; } -fn compressedEchoHandler(request: []const u8, allocator: std.mem.Allocator) ![]u8 { +fn compressedEchoHandler(request: []const u8, allocator: std.mem.Allocator, io: std.Io) ![]u8 { // Similar to echo but the server will compress the response - const timestamp = std.time.timestamp(); + const timestamp = std.Io.Timestamp.now(io, .real).toMilliseconds(); const response = try std.fmt.allocPrint( allocator, "CompressedEcho: {s} | Server: gRPC-zig | Time: {d}", @@ -75,16 +75,16 @@ fn compressedEchoHandler(request: []const u8, allocator: std.mem.Allocator) ![]u return response; } -fn healthCheckHandler(request: []const u8, allocator: std.mem.Allocator) ![]u8 { +fn healthCheckHandler(request: []const u8, allocator: std.mem.Allocator, _: std.Io) ![]u8 { _ = request; // Return a simple health status const response = try allocator.dupe(u8, "SERVING"); return response; } -fn secureEchoHandler(request: []const u8, allocator: std.mem.Allocator) ![]u8 { +fn secureEchoHandler(request: []const u8, allocator: std.mem.Allocator, io: std.Io) ![]u8 { // This handler expects authentication (will be handled by the server layer) - const timestamp = std.time.timestamp(); + const timestamp = std.Io.Timestamp.now(io, .real).toMilliseconds(); const response = try std.fmt.allocPrint( allocator, "SecureEcho: {s} | Server: gRPC-zig (authenticated) | Time: {d}", diff --git a/src/benchmark.zig b/src/benchmark.zig index fc8b53b..d8e9bcd 100644 --- a/src/benchmark.zig +++ b/src/benchmark.zig @@ -36,16 +36,18 @@ const BenchmarkResults = struct { // Simple benchmarking timer const Timer = struct { - start_time: i128, + io: std.Io, + start_time: i96, - fn start() Timer { + fn start(io: std.Io) Timer { return Timer{ - .start_time = std.time.nanoTimestamp(), + .io = io, + .start_time = std.Io.Timestamp.now(io, .awake).toNanoseconds(), }; } fn elapsed_ms(self: Timer) f64 { - const end_time = std.time.nanoTimestamp(); + const end_time = std.Io.Timestamp.now(self.io, .awake).toNanoseconds(); return @as(f64, @floatFromInt(end_time - self.start_time)) / 1_000_000.0; } }; @@ -53,12 +55,14 @@ const Timer = struct { // Test client worker const ClientWorker = struct { allocator: std.mem.Allocator, + io: std.Io, config: BenchmarkConfig, results: std.ArrayList(f64), - fn init(allocator: std.mem.Allocator, config: BenchmarkConfig) ClientWorker { + fn init(allocator: std.mem.Allocator, io: std.Io, config: BenchmarkConfig) ClientWorker { return ClientWorker{ .allocator = allocator, + .io = io, .config = config, .results = .empty, }; @@ -69,7 +73,7 @@ const ClientWorker = struct { } fn runBenchmark(self: *ClientWorker) !void { - var client = try GrpcClient.init(self.allocator, self.config.host, self.config.port); + var client = try GrpcClient.init(self.allocator, self.io, self.config.host, self.config.port); defer client.deinit(); try client.setAuth(self.config.secret_key); @@ -90,7 +94,7 @@ const ClientWorker = struct { // Actual benchmark requests for (0..self.config.num_requests) |_| { - const timer = Timer.start(); + const timer = Timer.start(self.io); const response = client.call("Benchmark", payload, .none) catch |err| { std.log.warn("Request failed: {}", .{err}); @@ -106,7 +110,7 @@ const ClientWorker = struct { fn generatePayload(self: *ClientWorker) ![]u8 { const payload = try self.allocator.alloc(u8, self.config.request_size_bytes); - var prng = std.Random.DefaultPrng.init(@as(u64, @intCast(std.time.milliTimestamp()))); + var prng = std.Random.DefaultPrng.init(@as(u64, @intCast(std.Io.Timestamp.now(self.io, .real).toMilliseconds()))); const random = prng.random(); for (payload) |*byte| { @@ -148,13 +152,13 @@ fn calculateLatencyStats(latencies: []f64) BenchmarkResults.LatencyStats { }; } -fn runBenchmark(allocator: std.mem.Allocator, config: BenchmarkConfig) !BenchmarkResults { +fn runBenchmark(allocator: std.mem.Allocator, io: std.Io, config: BenchmarkConfig) !BenchmarkResults { std.log.info("Starting benchmark with {} concurrent clients, {} requests each", .{ config.concurrent_clients, config.num_requests }); var all_latencies = try std.ArrayList(f64).initCapacity(allocator, config.concurrent_clients); defer all_latencies.deinit(allocator); - const overall_timer = Timer.start(); + const overall_timer = Timer.start(io); // Create and run client workers concurrently var workers = try std.ArrayList(ClientWorker).initCapacity(allocator, config.concurrent_clients); @@ -167,7 +171,7 @@ fn runBenchmark(allocator: std.mem.Allocator, config: BenchmarkConfig) !Benchmar // Initialize workers for (0..config.concurrent_clients) |_| { - const worker = ClientWorker.init(allocator, config); + const worker = ClientWorker.init(allocator, io, config); workers.appendAssumeCapacity(worker); } @@ -202,30 +206,34 @@ fn runBenchmark(allocator: std.mem.Allocator, config: BenchmarkConfig) !Benchmar .requests_per_second = requests_per_second, .latency_stats = calculateLatencyStats(all_latencies.items), .error_rate = @as(f64, @floatFromInt(total_failed)) / @as(f64, @floatFromInt(total_requests)), - .timestamp = std.time.timestamp(), + .timestamp = std.Io.Timestamp.now(io, .real).toSeconds(), }; } -fn outputResults(_: std.mem.Allocator, results: BenchmarkResults, format: Format) !void { +fn outputResults(io: std.Io, _: std.mem.Allocator, results: BenchmarkResults, format: Format) !void { switch (format) { .json => { - // Simple JSON output without using Stringify - std.debug.print("{{\n", .{}); - std.debug.print(" \"total_requests\": {},\n", .{results.total_requests}); - std.debug.print(" \"successful_requests\": {},\n", .{results.successful_requests}); - std.debug.print(" \"failed_requests\": {},\n", .{results.failed_requests}); - std.debug.print(" \"total_duration_ms\": {d:.2},\n", .{results.total_duration_ms}); - std.debug.print(" \"requests_per_second\": {d:.2},\n", .{results.requests_per_second}); - std.debug.print(" \"latency_stats\": {{\n", .{}); - std.debug.print(" \"min_ms\": {d:.2},\n", .{results.latency_stats.min_ms}); - std.debug.print(" \"max_ms\": {d:.2},\n", .{results.latency_stats.max_ms}); - std.debug.print(" \"avg_ms\": {d:.2},\n", .{results.latency_stats.avg_ms}); - std.debug.print(" \"p95_ms\": {d:.2},\n", .{results.latency_stats.p95_ms}); - std.debug.print(" \"p99_ms\": {d:.2}\n", .{results.latency_stats.p99_ms}); - std.debug.print(" }},\n", .{}); - std.debug.print(" \"error_rate\": {d:.4},\n", .{results.error_rate}); - std.debug.print(" \"timestamp\": {}\n", .{results.timestamp}); - std.debug.print("}}\n", .{}); + var stdout_buffer: [512]u8 = undefined; + var stdout_writer = std.Io.File.stdout().writer(io, &stdout_buffer); + const stdout = &stdout_writer.interface; + + try stdout.print("{{\n", .{}); + try stdout.print(" \"total_requests\": {},\n", .{results.total_requests}); + try stdout.print(" \"successful_requests\": {},\n", .{results.successful_requests}); + try stdout.print(" \"failed_requests\": {},\n", .{results.failed_requests}); + try stdout.print(" \"total_duration_ms\": {d:.2},\n", .{results.total_duration_ms}); + try stdout.print(" \"requests_per_second\": {d:.2},\n", .{results.requests_per_second}); + try stdout.print(" \"latency_stats\": {{\n", .{}); + try stdout.print(" \"min_ms\": {d:.2},\n", .{results.latency_stats.min_ms}); + try stdout.print(" \"max_ms\": {d:.2},\n", .{results.latency_stats.max_ms}); + try stdout.print(" \"avg_ms\": {d:.2},\n", .{results.latency_stats.avg_ms}); + try stdout.print(" \"p95_ms\": {d:.2},\n", .{results.latency_stats.p95_ms}); + try stdout.print(" \"p99_ms\": {d:.2}\n", .{results.latency_stats.p99_ms}); + try stdout.print(" }},\n", .{}); + try stdout.print(" \"error_rate\": {d:.4},\n", .{results.error_rate}); + try stdout.print(" \"timestamp\": {}\n", .{results.timestamp}); + try stdout.print("}}\n", .{}); + try stdout.flush(); }, .text => { std.debug.print("Benchmark Results:\n", .{}); @@ -248,37 +256,37 @@ fn outputResults(_: std.mem.Allocator, results: BenchmarkResults, format: Format pub const Format = enum { json, text }; -fn parseArgs(allocator: std.mem.Allocator) !struct { config: BenchmarkConfig, output_format: Format } { +fn parseArgs(allocator: std.mem.Allocator, args: std.process.Args) !struct { config: BenchmarkConfig, output_format: Format } { var config = BenchmarkConfig{}; var format: Format = .text; - const args = try std.process.argsAlloc(allocator); - defer std.process.argsFree(allocator, args); - - var i: usize = 1; - while (i < args.len) : (i += 1) { - if (std.mem.eql(u8, args[i], "--host") and i + 1 < args.len) { - config.host = try allocator.dupe(u8, args[i + 1]); - i += 1; - } else if (std.mem.eql(u8, args[i], "--port") and i + 1 < args.len) { - config.port = try std.fmt.parseInt(u16, args[i + 1], 10); - i += 1; - } else if (std.mem.eql(u8, args[i], "--requests") and i + 1 < args.len) { - config.num_requests = try std.fmt.parseInt(u32, args[i + 1], 10); - i += 1; - } else if (std.mem.eql(u8, args[i], "--clients") and i + 1 < args.len) { - config.concurrent_clients = try std.fmt.parseInt(u32, args[i + 1], 10); - i += 1; - } else if (std.mem.eql(u8, args[i], "--size") and i + 1 < args.len) { - config.request_size_bytes = try std.fmt.parseInt(u32, args[i + 1], 10); - i += 1; - } else if (std.mem.eql(u8, args[i], "--output") and i + 1 < args.len) { - if (std.mem.eql(u8, args[i + 1], "json")) { + var it = try args.iterateAllocator(allocator); + defer it.deinit(); + _ = it.skip(); + + while (it.next()) |arg| { + if (std.mem.eql(u8, arg, "--host")) { + const value = it.next() orelse continue; + config.host = try allocator.dupe(u8, value); + } else if (std.mem.eql(u8, arg, "--port")) { + const value = it.next() orelse continue; + config.port = try std.fmt.parseInt(u16, value, 10); + } else if (std.mem.eql(u8, arg, "--requests")) { + const value = it.next() orelse continue; + config.num_requests = try std.fmt.parseInt(u32, value, 10); + } else if (std.mem.eql(u8, arg, "--clients")) { + const value = it.next() orelse continue; + config.concurrent_clients = try std.fmt.parseInt(u32, value, 10); + } else if (std.mem.eql(u8, arg, "--size")) { + const value = it.next() orelse continue; + config.request_size_bytes = try std.fmt.parseInt(u32, value, 10); + } else if (std.mem.eql(u8, arg, "--output")) { + const value = it.next() orelse continue; + if (std.mem.eql(u8, value, "json")) { format = .json; - } else if (std.mem.eql(u8, args[i + 1], "text")) { + } else if (std.mem.eql(u8, value, "text")) { format = .text; } - i += 1; - } else if (std.mem.eql(u8, args[i], "--help")) { + } else if (std.mem.eql(u8, arg, "--help")) { printUsage(); std.process.exit(0); } @@ -302,18 +310,18 @@ fn printUsage() void { } // Simple benchmark handler for testing -pub fn benchmarkHandler(request: []const u8, allocator: std.mem.Allocator) ![]u8 { +pub fn benchmarkHandler(request: []const u8, allocator: std.mem.Allocator, io: std.Io) ![]u8 { // Echo the request back with a timestamp - const response = try std.fmt.allocPrint(allocator, "Echo: {s} (processed at {})", .{ request, std.time.milliTimestamp() }); + const response = try std.fmt.allocPrint(allocator, "Echo: {s} (processed at {})", .{ request, std.Io.Timestamp.now(io, .real).toMilliseconds() }); return response; } -pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); +pub fn main(init: std.process.Init) !void { + var safe_allocator = std.heap.SafeAllocator.init(init.gpa, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); - const parsed = try parseArgs(allocator); + const parsed = try parseArgs(allocator, init.minimal.args); const config = parsed.config; const output_format = parsed.output_format; // Free the duplicated host string at the end @@ -327,6 +335,6 @@ pub fn main() !void { std.debug.print(" Request size: {} bytes", .{config.request_size_bytes}); std.debug.print(" Output format: {}", .{output_format}); - const results = try runBenchmark(allocator, config); - try outputResults(allocator, results, output_format); + const results = try runBenchmark(allocator, init.io, config); + try outputResults(init.io, allocator, results, output_format); } diff --git a/src/client.zig b/src/client.zig index 2bb7076..5acc18f 100644 --- a/src/client.zig +++ b/src/client.zig @@ -9,16 +9,19 @@ const health = @import("features/health.zig"); pub const GrpcClient = struct { allocator: std.mem.Allocator, + io: std.Io, transport: transport.Transport, compression: compression.Compression, auth: ?auth.Auth, - pub fn init(allocator: std.mem.Allocator, host: []const u8, port: u16) !GrpcClient { - const connection = try std.net.tcpConnectToHost(allocator, host, port); + pub fn init(allocator: std.mem.Allocator, io: std.Io, host: []const u8, port: u16) !GrpcClient { + const hostname = try std.Io.net.HostName.init(host); + const connection = try hostname.connect(io, port, .{ .mode = .stream }); return GrpcClient{ .allocator = allocator, - .transport = try transport.Transport.initClient(allocator, connection), + .io = io, + .transport = try transport.Transport.initClient(allocator, io, connection), .compression = compression.Compression.init(allocator), .auth = null, }; @@ -29,7 +32,7 @@ pub const GrpcClient = struct { } pub fn setAuth(self: *GrpcClient, secret_key: []const u8) !void { - self.auth = auth.Auth.init(self.allocator, secret_key); + self.auth = auth.Auth.init(self.allocator, self.io, secret_key); } pub fn checkHealth(self: *GrpcClient, service: []const u8) !health.HealthStatus { diff --git a/src/features/auth.zig b/src/features/auth.zig index bfbb689..61d70d9 100644 --- a/src/features/auth.zig +++ b/src/features/auth.zig @@ -21,10 +21,12 @@ pub const Auth = struct { secret_key: []const u8, allocator: std.mem.Allocator, + io: std.Io, - pub fn init(allocator: std.mem.Allocator, secret_key: []const u8) Auth { + pub fn init(allocator: std.mem.Allocator, io: std.Io, secret_key: []const u8) Auth { return .{ .allocator = allocator, + .io = io, .secret_key = secret_key, }; } @@ -41,7 +43,7 @@ pub const Auth = struct { hash.update(header_b64); hash.update("."); hash.update(payload_b64); - + var expected_signature: [crypto.hmac.sha256.mac_length]u8 = undefined; hash.final(&expected_signature); @@ -51,7 +53,7 @@ pub const Auth = struct { } pub fn generateToken(self: *Auth, subject: []const u8, expires_in: i64) ![]u8 { - const now = std.time.timestamp(); + const now = std.Io.Timestamp.now(self.io, .real).toSeconds(); // Simplified JWT creation without JSON - just create a simple token string // Format: "HS256.JWT.{subject}.{exp}.{iat}" diff --git a/src/features/compression.zig b/src/features/compression.zig index 65acbeb..4b0858e 100644 --- a/src/features/compression.zig +++ b/src/features/compression.zig @@ -1,7 +1,5 @@ const std = @import("std"); -const c = @cImport({ - @cInclude("zlib.h"); -}); +const c = @import("zlib"); pub const CompressionError = error{ CompressionFailed, @@ -105,4 +103,4 @@ pub const Compression = struct { }, } } -}; \ No newline at end of file +}; diff --git a/src/features/streaming.zig b/src/features/streaming.zig index 0029d42..4af82a9 100644 --- a/src/features/streaming.zig +++ b/src/features/streaming.zig @@ -17,7 +17,7 @@ pub const MessageStream = struct { pub fn init(allocator: std.mem.Allocator, max_buffer_size: usize) MessageStream { return .{ - .buffer = std.ArrayList(StreamingMessage){}, + .buffer = .empty, .allocator = allocator, .max_buffer_size = max_buffer_size, }; @@ -46,4 +46,4 @@ pub const MessageStream = struct { if (self.buffer.items.len == 0) return null; return self.buffer.orderedRemove(0); } -}; \ No newline at end of file +}; diff --git a/src/http2/hpack.zig b/src/http2/hpack.zig index 90e1a60..e47136b 100644 --- a/src/http2/hpack.zig +++ b/src/http2/hpack.zig @@ -26,7 +26,7 @@ pub const Encoder = struct { } pub fn encode(self: *Encoder, headers: std.StringHashMap([]const u8)) ![]u8 { - var buffer = std.ArrayList(u8){}; + var buffer: std.ArrayList(u8) = .empty; errdefer buffer.deinit(self.allocator); var it = headers.iterator(); diff --git a/src/server.zig b/src/server.zig index 28b16a0..36e3b57 100644 --- a/src/server.zig +++ b/src/server.zig @@ -9,35 +9,37 @@ const health = @import("features/health.zig"); pub const Handler = struct { name: []const u8, - handler_fn: *const fn ([]const u8, std.mem.Allocator) anyerror![]u8, + handler_fn: *const fn ([]const u8, std.mem.Allocator, std.Io) anyerror![]u8, }; pub const GrpcServer = struct { allocator: std.mem.Allocator, - address: std.net.Address, - server: std.net.Server, + io: std.Io, + address: std.Io.net.IpAddress, + server: std.Io.net.Server, handlers: std.ArrayList(Handler), compression: compression.Compression, auth: auth.Auth, health_check: health.HealthCheck, - pub fn init(allocator: std.mem.Allocator, port: u16, secret_key: []const u8) !GrpcServer { - const address = try std.net.Address.parseIp("127.0.0.1", port); - const server = try address.listen(.{ .reuse_address = false }); + pub fn init(allocator: std.mem.Allocator, io: std.Io, port: u16, secret_key: []const u8) !GrpcServer { + const address = try std.Io.net.IpAddress.parse("127.0.0.1", port); + const server = try address.listen(io, .{ .reuse_address = false }); return GrpcServer{ .allocator = allocator, + .io = io, .address = address, .server = server, .handlers = try std.ArrayList(Handler).initCapacity(allocator, 1), .compression = compression.Compression.init(allocator), - .auth = auth.Auth.init(allocator, secret_key), + .auth = auth.Auth.init(allocator, io, secret_key), .health_check = health.HealthCheck.init(allocator), }; } pub fn deinit(self: *GrpcServer) void { self.handlers.deinit(self.allocator); - self.server.deinit(); + self.server.deinit(self.io); self.health_check.deinit(); } @@ -45,17 +47,17 @@ pub const GrpcServer = struct { try self.health_check.setStatus("grpc.health.v1.Health", .SERVING); while (true) { - const connection = try self.server.accept(); + const stream = try self.server.accept(self.io); // Handle connection errors gracefully - don't crash the server - self.handleConnection(connection) catch |err| { + self.handleConnection(stream) catch |err| { std.log.err("Connection handling failed: {}", .{err}); continue; }; } } - fn handleConnection(self: *GrpcServer, conn: std.net.Server.Connection) !void { - var trans = try transport.Transport.initServer(self.allocator, conn.stream); + fn handleConnection(self: *GrpcServer, stream: std.Io.net.Stream) !void { + var trans = try transport.Transport.initServer(self.allocator, self.io, stream); defer trans.deinit(); // Setup streaming @@ -83,7 +85,7 @@ pub const GrpcServer = struct { // TODO: Implement proper method routing based on request headers if (self.handlers.items.len > 0) { const handler = self.handlers.items[0]; - const response = try handler.handler_fn(decompressed, self.allocator); + const response = try handler.handler_fn(decompressed, self.allocator, self.io); defer self.allocator.free(response); // Use same compression as request diff --git a/src/tests.zig b/src/tests.zig index 4d392b8..0ddc60a 100644 --- a/src/tests.zig +++ b/src/tests.zig @@ -29,12 +29,12 @@ const benchmark = @import("benchmark.zig"); // } test "benchmark handler" { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); + var safe_allocator = std.heap.SafeAllocator.init(testing.allocator, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); const request = "test_request"; - const response = try benchmark.benchmarkHandler(request, allocator); + const response = try benchmark.benchmarkHandler(request, allocator, std.testing.io); defer allocator.free(response); // Verify response contains the request @@ -46,14 +46,18 @@ test "benchmark handler" { test "compression - gzip" { const compression = @import("features/compression.zig"); - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); + var safe_allocator = std.heap.SafeAllocator.init(testing.allocator, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); var comp = compression.Compression.init(allocator); // Test data - const original = "Hello, World! This is a test of gzip compression. " ** 10; + const chunk = "Hello, World! This is a test of gzip compression. "; + const original: []const u8 = blk: { + const buf: [10][chunk.len]u8 = @splat(chunk[0..chunk.len].*); + break :blk @ptrCast(&buf); + }; // Compress const compressed = try comp.compress(original, .gzip); @@ -73,14 +77,18 @@ test "compression - gzip" { test "compression - deflate" { const compression = @import("features/compression.zig"); - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); + var safe_allocator = std.heap.SafeAllocator.init(testing.allocator, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); var comp = compression.Compression.init(allocator); // Test data - const original = "Deflate compression test data. " ** 20; + const chunk = "Deflate compression test data. "; + const original: []const u8 = blk: { + const buf: [20][chunk.len]u8 = @splat(chunk[0..chunk.len].*); + break :blk @ptrCast(&buf); + }; // Compress const compressed = try comp.compress(original, .deflate); @@ -100,9 +108,9 @@ test "compression - deflate" { test "compression - none algorithm" { const compression = @import("features/compression.zig"); - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - defer _ = gpa.deinit(); - const allocator = gpa.allocator(); + var safe_allocator = std.heap.SafeAllocator.init(testing.allocator, .{}); + defer _ = safe_allocator.deinit(); + const allocator = safe_allocator.allocator(); var comp = compression.Compression.init(allocator); @@ -121,4 +129,4 @@ test "compression - none algorithm" { defer allocator.free(decompressed); try testing.expectEqualStrings(original, decompressed); -} \ No newline at end of file +} diff --git a/src/transport.zig b/src/transport.zig index 7a79fac..9f9a65d 100644 --- a/src/transport.zig +++ b/src/transport.zig @@ -1,5 +1,5 @@ const std = @import("std"); -const net = std.net; +const net = std.Io.net; const http2 = struct { pub const connection = @import("http2/connection.zig"); pub const frame = @import("http2/frame.zig"); @@ -16,14 +16,16 @@ pub const TransportError = error{ pub const Transport = struct { stream: net.Stream, + io: std.Io, read_buf: []u8, write_buf: []u8, allocator: std.mem.Allocator, http2_conn: ?http2.connection.Connection, - pub fn initClient(allocator: std.mem.Allocator, stream: net.Stream) !Transport { + pub fn initClient(allocator: std.mem.Allocator, io: std.Io, stream: net.Stream) !Transport { var transport = Transport{ .stream = stream, + .io = io, .read_buf = try allocator.alloc(u8, 1024 * 64), .write_buf = try allocator.alloc(u8, 1024 * 64), .allocator = allocator, @@ -37,14 +39,16 @@ pub const Transport = struct { return transport; } - pub fn initServer(allocator: std.mem.Allocator, stream: net.Stream) !Transport { + pub fn initServer(allocator: std.mem.Allocator, io: std.Io, stream: net.Stream) !Transport { var transport = Transport{ .stream = stream, + .io = io, .read_buf = try allocator.alloc(u8, 1024 * 64), .write_buf = try allocator.alloc(u8, 1024 * 64), .allocator = allocator, .http2_conn = null, }; + errdefer transport.deinit(); // Initialize HTTP/2 connection transport.http2_conn = try http2.connection.Connection.init(allocator); @@ -59,28 +63,27 @@ pub const Transport = struct { } self.allocator.free(self.read_buf); self.allocator.free(self.write_buf); - self.stream.close(); + self.stream.close(self.io); } fn setupHttp2Client(self: *Transport) !void { // Client sends HTTP/2 connection preface - _ = try self.stream.write(http2.connection.Connection.PREFACE); + try self.writeAll(http2.connection.Connection.PREFACE); // Send initial SETTINGS frame const settings_header: [9]u8 = .{ - 0, 0, 0, // length: 0 (no settings parameters) + 0, 0, 0, // length: 0 (no settings parameters) @intFromEnum(http2.frame.FrameType.SETTINGS), 0, // flags: none 0, 0, 0, 0, // stream_id: 0 }; - _ = try self.stream.write(&settings_header); + try self.writeAll(&settings_header); } fn setupHttp2Server(self: *Transport) !void { // Server receives and validates HTTP/2 connection preface var preface_buf: [24]u8 = undefined; - const bytes_read = try self.stream.read(&preface_buf); - if (bytes_read < 24) return TransportError.ConnectionClosed; + try self.readExact(&preface_buf); // Validate preface if (!std.mem.eql(u8, &preface_buf, http2.connection.Connection.PREFACE)) { @@ -89,45 +92,43 @@ pub const Transport = struct { // Read client's SETTINGS frame var settings_header: [9]u8 = undefined; - const settings_read = try self.stream.read(&settings_header); - if (settings_read < 9) return TransportError.ConnectionClosed; + try self.readExact(&settings_header); // TODO: Parse and process SETTINGS frame properly // For now, just skip the payload if any const settings_length = (@as(u24, settings_header[0]) << 16) | - (@as(u24, settings_header[1]) << 8) | - @as(u24, settings_header[2]); + (@as(u24, settings_header[1]) << 8) | + @as(u24, settings_header[2]); if (settings_length > 0) { const settings_payload = try self.allocator.alloc(u8, settings_length); defer self.allocator.free(settings_payload); - _ = try self.stream.read(settings_payload); + try self.readExact(settings_payload); } // Send server's SETTINGS frame const settings_response: [9]u8 = .{ - 0, 0, 0, // length: 0 + 0, 0, 0, // length: 0 @intFromEnum(http2.frame.FrameType.SETTINGS), 0, // flags: none 0, 0, 0, 0, // stream_id: 0 }; - _ = try self.stream.write(&settings_response); + try self.writeAll(&settings_response); // Send SETTINGS ACK for client's settings const settings_ack: [9]u8 = .{ - 0, 0, 0, // length: 0 + 0, 0, 0, // length: 0 @intFromEnum(http2.frame.FrameType.SETTINGS), 0x1, // flags: ACK 0, 0, 0, 0, // stream_id: 0 }; - _ = try self.stream.write(&settings_ack); + try self.writeAll(&settings_ack); } pub fn readMessage(self: *Transport) ![]const u8 { // Read frame header first (9 bytes) const header_size = 9; var header: [header_size]u8 = undefined; - const bytes_read = try self.stream.read(&header); - if (bytes_read < header_size) return TransportError.ConnectionClosed; + try self.readExact(&header); // Parse header manually const length = (@as(u24, header[0]) << 16) | (@as(u24, header[1]) << 8) | @as(u24, header[2]); @@ -138,10 +139,7 @@ pub const Transport = struct { errdefer self.allocator.free(payload); if (length > 0) { - const payload_read = try self.stream.read(payload); - if (payload_read < length) { - return TransportError.ConnectionClosed; - } + try self.readExact(payload); } // For DATA frames, return payload @@ -170,9 +168,44 @@ pub const Transport = struct { header[7] = @intCast((stream_id >> 8) & 0xFF); header[8] = @intCast(stream_id & 0xFF); - _ = try self.stream.write(&header); + try self.writeAll(&header); if (message.len > 0) { - _ = try self.stream.write(message); + try self.writeAll(message); + } + } + + fn readOnce(self: *Transport, buffer: []u8) !usize { + var data: [1][]u8 = .{buffer}; + return self.stream.read(self.io, &data) catch |err| switch (err) { + error.SocketUnconnected, error.ConnectionResetByPeer => 0, + else => return err, + }; + } + + fn readExact(self: *Transport, buffer: []u8) !void { + var offset: usize = 0; + while (offset < buffer.len) { + const bytes_read = try self.readOnce(buffer[offset..]); + if (bytes_read == 0) return TransportError.ConnectionClosed; + offset += bytes_read; + } + } + + fn writeAll(self: *Transport, bytes: []const u8) !void { + var remaining = bytes; + while (remaining.len > 0) { + const written = self.io.vtable.netWrite( + self.io.userdata, + self.stream.socket.handle, + "", + &.{remaining}, + 1, + ) catch |err| switch (err) { + error.SocketUnconnected, error.ConnectionResetByPeer => return, + else => return err, + }; + if (written == 0) return; + remaining = remaining[written..]; } } };