const std = @import("std"); const abi = @import("abi.zig"); const config = @import("config.zig"); const http_executor = @import("protocol/http_executor.zig"); const http_state = @import("protocol/http_state.zig"); const runner_log = @import("runner/log.zig"); const runner_metrics = @import("runner/metrics.zig"); const template = @import("template.zig"); pub const transport_abi_version: u32 = 1; pub const exporter_abi_version: u32 = 1; pub const Kind = enum { transport, exporter, }; const ManifestFile = struct { name: []const u8, kind: Kind, abi_version: u32, version: []const u8 = "0.0.0", command: []const u8, args: []const []const u8 = &.{}, }; const ResolvedPlugin = struct { name: []u8, version: []u8, kind: Kind, abi_version: u32, argv: []const []const u8, fn deinit(self: *ResolvedPlugin, allocator: std.mem.Allocator) void { allocator.free(self.name); allocator.free(self.version); for (self.argv) |arg| allocator.free(arg); allocator.free(self.argv); self.* = undefined; } }; const HeaderEntry = struct { name: []const u8, value: []const u8, }; const TransportRequest = struct { abi_version: u32 = transport_abi_version, protocol: []const u8, target: []const u8, method: []const u8, path: []const u8, headers: []const HeaderEntry, body_base64: []const u8, connect_timeout_ms: u32, timeout_ms: u32, delay_before_ms: u32, capture_body_max_bytes: u32, }; const TransportResponse = struct { abi_version: u32 = transport_abi_version, success: bool, status_code: u16 = 0, transport_code: []const u8 = "none", timeout_phase: []const u8 = "none", headers: []const HeaderEntry = &.{}, body_base64: ?[]const u8 = null, body_truncated: bool = false, grpc_status: ?u8 = null, grpc_deadline_exceeded: bool = false, }; const ExporterRequest = struct { abi_version: u32 = exporter_abi_version, scenario_name: []const u8, scenario_mode: []const u8, protocol: []const u8, summary: runner_metrics.FinalSummary.Output, config: []const config.HeaderTemplate, }; pub fn executeTransport( allocator: std.mem.Allocator, scenario: *const config.ScenarioConfig, store: *const template.VarStore, cookie_jar: ?*const http_state.CookieJar, target: []const u8, method: config.HttpMethod, path_template: []const u8, header_templates: []const config.HeaderTemplate, body_template: ?[]const u8, body_override: ?[]const u8, connect_timeout_ms: u32, timeout_ms: u32, delay_before_ms: u32, capture_body_max_bytes: u32, ) !http_executor.RequestExecution { const plugin_name = scenario.http.transport_plugin orelse return error.TransportPluginNotConfigured; const plugin_dir = scenario.plugins.dir orelse return error.PluginDirectoryRequired; var plugin = try discoverPlugin(allocator, plugin_dir, plugin_name, .transport); defer plugin.deinit(allocator); const rendered_path = try template.render(allocator, path_template, store, .path); defer allocator.free(rendered_path); const rendered_body = if (body_override) |body| try allocator.dupe(u8, body) else if (body_template) |body| try template.render(allocator, body, store, .body) else try allocator.dupe(u8, ""); defer allocator.free(rendered_body); var rendered_headers = std.ArrayList(config.HeaderTemplate).empty; defer { for (rendered_headers.items) |header| allocator.free(header.value); rendered_headers.deinit(allocator); } for (header_templates) |header| { try rendered_headers.append(allocator, .{ .key = header.key, .value = try template.render(allocator, header.value, store, .header), }); } if (cookie_jar) |jar| { const cookie = try jar.headerValue(allocator); defer if (cookie) |value| allocator.free(value); if (cookie) |value| { try rendered_headers.append(allocator, .{ .key = "Cookie", .value = try allocator.dupe(u8, value) }); } } const encoded_body = try encodeBase64(allocator, rendered_body); defer allocator.free(encoded_body); var request_headers = try allocator.alloc(HeaderEntry, rendered_headers.items.len); defer allocator.free(request_headers); for (rendered_headers.items, 0..) |header, index| { request_headers[index] = .{ .name = header.key, .value = header.value }; } const started = std.time.nanoTimestamp(); var response = try invokeJsonPlugin(allocator, &plugin, TransportRequest{ .protocol = @tagName(scenario.scenario.protocol), .target = target, .method = @tagName(method), .path = rendered_path, .headers = request_headers, .body_base64 = encoded_body, .connect_timeout_ms = connect_timeout_ms, .timeout_ms = timeout_ms, .delay_before_ms = delay_before_ms, .capture_body_max_bytes = capture_body_max_bytes, }, TransportResponse); defer response.parsed.deinit(); const duration_nanos: u64 = @intCast(@max(std.time.nanoTimestamp() - started, 0)); const decoded_body = if (response.parsed.value.body_base64) |encoded| try decodeBase64Alloc(allocator, encoded) else null; var owned_headers = try allocator.alloc(http_state.OwnedHeader, response.parsed.value.headers.len); errdefer http_state.clearOwnedHeaders(allocator, owned_headers); for (response.parsed.value.headers, 0..) |header, index| { owned_headers[index] = .{ .name = try allocator.dupe(u8, header.name), .value = try allocator.dupe(u8, header.value), }; } return .{ .status_code = response.parsed.value.status_code, .duration_nanos = duration_nanos, .bytes_sent = rendered_body.len, .bytes_received = if (decoded_body) |body| body.len else 0, .success = response.parsed.value.success, .transport_code = try parseTransportCode(response.parsed.value.transport_code), .timeout_phase = parseTimeoutPhase(response.parsed.value.timeout_phase), .grpc_status = response.parsed.value.grpc_status, .deadline_exceeded = response.parsed.value.grpc_deadline_exceeded, .body_truncated = response.parsed.value.body_truncated, .headers = owned_headers, .captured_body = decoded_body, }; } pub fn writeExporter( allocator: std.mem.Allocator, scenario: *const config.ScenarioConfig, exporter_config: config.PluginExporter, summary: *const runner_metrics.FinalSummary, ) !void { const plugin_dir = scenario.plugins.dir orelse return error.PluginDirectoryRequired; var plugin = try discoverPlugin(allocator, plugin_dir, exporter_config.name, .exporter); defer plugin.deinit(allocator); var response = try invokeJsonPlugin(allocator, &plugin, ExporterRequest{ .scenario_name = scenario.scenario.name, .scenario_mode = scenario.scenario.mode().label(), .protocol = @tagName(scenario.scenario.protocol), .summary = summary.output, .config = exporter_config.config, }, struct { abi_version: u32 = exporter_abi_version, ok: bool = true, message: ?[]const u8 = null, }); defer response.parsed.deinit(); } fn discoverPlugin( allocator: std.mem.Allocator, dir_path: []const u8, name: []const u8, kind: Kind, ) !ResolvedPlugin { var dir = try std.fs.cwd().openDir(dir_path, .{ .iterate = true }); defer dir.close(); var iterator = dir.iterate(); while (try iterator.next()) |entry| { if (entry.kind != .file) continue; if (!std.mem.endsWith(u8, entry.name, ".json")) continue; const manifest_bytes = try dir.readFileAlloc(allocator, entry.name, 1024 * 1024); defer allocator.free(manifest_bytes); var parsed = try std.json.parseFromSlice(ManifestFile, allocator, manifest_bytes, .{}); defer parsed.deinit(); if (!std.mem.eql(u8, parsed.value.name, name)) continue; if (parsed.value.kind != kind) continue; const expected_abi = switch (kind) { .transport => transport_abi_version, .exporter => exporter_abi_version, }; if (parsed.value.abi_version != expected_abi) return error.PluginAbiVersionMismatch; return .{ .name = try allocator.dupe(u8, parsed.value.name), .version = try allocator.dupe(u8, parsed.value.version), .kind = parsed.value.kind, .abi_version = parsed.value.abi_version, .argv = try buildArgv(allocator, dir_path, parsed.value), }; } return error.PluginNotFound; } fn buildArgv(allocator: std.mem.Allocator, dir_path: []const u8, manifest: ManifestFile) ![]const []const u8 { var argv = try allocator.alloc([]const u8, manifest.args.len + 1); errdefer { for (argv[0 .. manifest.args.len + 1]) |arg| { if (arg.len != 0) allocator.free(arg); } allocator.free(argv); } argv[0] = try resolveCommandPath(allocator, dir_path, manifest.command); for (manifest.args, 0..) |arg, index| { argv[index + 1] = if (isRelativePathLiteral(arg)) try resolveCommandPath(allocator, dir_path, arg) else try allocator.dupe(u8, arg); } return argv; } fn resolveCommandPath(allocator: std.mem.Allocator, dir_path: []const u8, path: []const u8) ![]u8 { if (!isRelativePathLiteral(path)) return try allocator.dupe(u8, path); return try std.fs.path.resolve(allocator, &.{ dir_path, path }); } fn isRelativePathLiteral(value: []const u8) bool { return std.mem.startsWith(u8, value, "./") or std.mem.startsWith(u8, value, "../"); } fn invokeJsonPlugin( allocator: std.mem.Allocator, plugin: *const ResolvedPlugin, request_value: anytype, comptime ResponseType: type, ) !struct { parsed: std.json.Parsed(ResponseType) } { var request_writer: std.Io.Writer.Allocating = .init(allocator); defer request_writer.deinit(); try std.json.Stringify.value(request_value, .{}, &request_writer.writer); var child = std.process.Child.init(plugin.argv, allocator); child.stdin_behavior = .Pipe; child.stdout_behavior = .Pipe; child.stderr_behavior = .Pipe; try child.spawn(); errdefer _ = child.kill() catch {}; if (child.stdin) |stdin| { try stdin.writeAll(request_writer.writer.buffered()); stdin.close(); child.stdin = null; } var stdout = std.ArrayList(u8).empty; defer stdout.deinit(allocator); var stderr = std.ArrayList(u8).empty; defer stderr.deinit(allocator); try child.collectOutput(allocator, &stdout, &stderr, 1024 * 1024); const term = try child.wait(); switch (term) { .Exited => |code| if (code != 0) return error.PluginCommandFailed, else => return error.PluginCommandFailed, } return .{ .parsed = try std.json.parseFromSlice(ResponseType, allocator, stdout.items, .{}), }; } fn parseTransportCode(raw: []const u8) !abi.TransportCode { if (std.mem.eql(u8, raw, "none")) return .none; if (std.mem.eql(u8, raw, "dns")) return .dns; if (std.mem.eql(u8, raw, "connect")) return .connect; if (std.mem.eql(u8, raw, "tls")) return .tls; if (std.mem.eql(u8, raw, "write")) return .write; if (std.mem.eql(u8, raw, "read")) return .read; if (std.mem.eql(u8, raw, "timeout")) return .timeout; if (std.mem.eql(u8, raw, "protocol")) return .protocol; return error.InvalidTransportCode; } fn parseTimeoutPhase(raw: []const u8) http_executor.TimeoutPhase { if (std.mem.eql(u8, raw, "connect")) return .connect; if (std.mem.eql(u8, raw, "io")) return .io; return .none; } fn encodeBase64(allocator: std.mem.Allocator, bytes: []const u8) ![]u8 { const encoded = try allocator.alloc(u8, std.base64.standard.Encoder.calcSize(bytes.len)); _ = std.base64.standard.Encoder.encode(encoded, bytes); return encoded; } fn decodeBase64Alloc(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { const decoded_len = try std.base64.standard.Decoder.calcSizeForSlice(encoded); const decoded = try allocator.alloc(u8, decoded_len); errdefer allocator.free(decoded); try std.base64.standard.Decoder.decode(decoded, encoded); return decoded; } test "parse transport code labels" { try std.testing.expectEqual(abi.TransportCode.timeout, try parseTransportCode("timeout")); try std.testing.expectEqual(abi.TransportCode.protocol, try parseTransportCode("protocol")); } test "discover exporter plugin from manifest directory" { var tmp_dir = std.testing.tmpDir(.{}); defer tmp_dir.cleanup(); try tmp_dir.dir.writeFile(.{ .sub_path = "manifest.json", .data = \\{ \\ "name": "csv", \\ "kind": "exporter", \\ "abi_version": 1, \\ "version": "1.2.3", \\ "command": "/bin/sh", \\ "args": ["./plugin.sh"] \\} , }); try tmp_dir.dir.writeFile(.{ .sub_path = "plugin.sh", .data = "#!/bin/sh\nprintf '{\"abi_version\":1,\"ok\":true}\\n'\n" }); const dir_path = try std.fmt.allocPrint(std.testing.allocator, ".zig-cache/tmp/{s}", .{tmp_dir.sub_path}); defer std.testing.allocator.free(dir_path); var plugin = try discoverPlugin(std.testing.allocator, dir_path, "csv", .exporter); defer plugin.deinit(std.testing.allocator); try std.testing.expectEqualStrings("csv", plugin.name); try std.testing.expectEqualStrings("1.2.3", plugin.version); try std.testing.expectEqual(@as(usize, 2), plugin.argv.len); } test "write exporter invokes plugin command" { var tmp_dir = std.testing.tmpDir(.{}); defer tmp_dir.cleanup(); try tmp_dir.dir.writeFile(.{ .sub_path = "manifest.json", .data = \\{ \\ "name": "csv", \\ "kind": "exporter", \\ "abi_version": 1, \\ "version": "0.1.0", \\ "command": "/bin/sh", \\ "args": ["./plugin.sh"] \\} , }); try tmp_dir.dir.writeFile(.{ .sub_path = "plugin.sh", .data = \\#!/bin/sh \\set -eu \\payload="$(cat)" \\out_path="$(printf '%s' "$payload" | sed -n 's/.*"key":"path","value":"\([^"]*\)".*/\1/p')" \\printf '%s' "$payload" >"$out_path" \\printf '{"abi_version":1,"ok":true}\n' , }); const dir_path = try std.fmt.allocPrint(std.testing.allocator, ".zig-cache/tmp/{s}", .{tmp_dir.sub_path}); defer std.testing.allocator.free(dir_path); const out_path = try std.fmt.allocPrint(std.testing.allocator, ".zig-cache/tmp/{s}/out.json", .{tmp_dir.sub_path}); defer std.testing.allocator.free(out_path); const scenario = config.ScenarioConfig{ .arena = undefined, .scenario = .{ .name = "plugin-test", .protocol = .http, .target = "https://example.internal" }, .execution = .{ .mode = .constant_vus, .duration = .{ .nanos = 1 }, .vus = 1 }, .plugins = .{ .dir = dir_path }, .setup = .{ .requests = &.{} }, .http = .{ .defaults = .{}, .requests = &.{} }, .exporters = .{ .plugins = &.{ .{ .name = "csv", .config = &.{.{ .key = "path", .value = out_path }} }, }, }, .thresholds = &.{}, }; var measured = std.mem.zeroes(runner_metrics.WindowSummary); measured.requests_total = 7; defer measured.deinit(std.testing.allocator); var warmup = std.mem.zeroes(runner_metrics.WindowSummary); defer warmup.deinit(std.testing.allocator); var summary = runner_metrics.FinalSummary{ .allocator = std.testing.allocator, .output = .{ .schema_version = 2, .scenario_name = "plugin-test", .scenario_mode = "simple", .wasm_backend = "wamr", .interrupted = false, .measured = measured, .warmup = warmup, .thresholds_failed = false, }, .threshold_failed = false, }; try writeExporter(std.testing.allocator, &scenario, scenario.exporters.plugins[0], &summary); const written = try tmp_dir.dir.readFileAlloc(std.testing.allocator, "out.json", 16 * 1024); defer std.testing.allocator.free(written); try std.testing.expect(std.mem.indexOf(u8, written, "\"scenario_name\":\"plugin-test\"") != null); }