Something went wrong. Try again.
xburner is an experimental HTTP and gRPC load generator written in Zig.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751const std = @import("std");
const cli = @import("cli.zig");const config = @import("config.zig");const contracts = @import("contracts.zig");const runner = @import("runner.zig");const runner_context = @import("runner/context.zig");const runner_control = @import("runner/control.zig");const runner_entry = @import("runner/entry.zig");const runner_exporter = @import("runner/exporter.zig");const runner_log = @import("runner/log.zig");const runner_metrics = @import("runner/metrics.zig");const runner_observation = @import("runner/observation.zig");const runner_orchestration = @import("runner/orchestration.zig");const template = @import("template.zig");const workflow_scenario = @import("workflow/scenario.zig");
pub const protocol_version: u32 = 1;
const KeyValueEntry = template.SnapshotEntry;
const RunRequest = struct { schema_version: u32 = protocol_version, kind: []const u8 = "run", coordinator_unix_nanos: i128, expanded_config_source: []const u8, env: []const KeyValueEntry, initial_store: []const KeyValueEntry, shard_index: u32, shard_count: u32, wasm_backend: ?[]const u8 = null, wasm_module_base64: ?[]const u8 = null, tls_ca_pem_base64: ?[]const u8 = null,};
const RunResponse = struct { schema_version: u32 = protocol_version, kind: []const u8 = "run_result", shard_index: u32, agent_unix_nanos: i128, clock_skew_nanos: i128, ok: bool, exit_code: u8 = contracts.ExitCode.invalid_config.code(), error_message: ?[]const u8 = null, snapshot: ?runner_metrics.AggregatorSnapshot = null,
fn deinit(self: *RunResponse, allocator: std.mem.Allocator) void { if (self.error_message) |message| allocator.free(message); if (self.snapshot) |*snapshot| snapshot.deinit(allocator); self.* = undefined; }};
const FileBlob = struct { base64: ?[]u8 = null,
fn deinit(self: *FileBlob, allocator: std.mem.Allocator) void { if (self.base64) |bytes| allocator.free(bytes); self.* = undefined; }};
const MaterializedFiles = struct { wasm_path: ?[]u8 = null, ca_file_path: ?[]u8 = null,
fn deinit(self: *MaterializedFiles, allocator: std.mem.Allocator) void { if (self.wasm_path) |path| { std.fs.cwd().deleteFile(path) catch {}; allocator.free(path); } if (self.ca_file_path) |path| { std.fs.cwd().deleteFile(path) catch {}; allocator.free(path); } self.* = undefined; }};
const AgentInvocation = struct { allocator: std.mem.Allocator, address: []const u8, request: RunRequest, response: ?RunResponse = null, err: ?anyerror = null, thread: ?std.Thread = null,
fn start(self: *AgentInvocation) !void { self.thread = try std.Thread.spawn(.{}, runThread, .{self}); }
fn join(self: *AgentInvocation) void { if (self.thread) |thread| { thread.join(); self.thread = null; } }
fn runThread(self: *AgentInvocation) void { self.err = null; self.response = null; self.run() catch |err| { self.err = err; }; }
fn run(self: *AgentInvocation) !void { self.response = try sendRunRequest(self.allocator, self.address, &self.request); }};
pub fn serveAgent(allocator: std.mem.Allocator, listen_address: []const u8, stderr: anytype) !contracts.ExitCode { var stderr_holder = runner_log.WriterHolder(@TypeOf(stderr)).init(stderr); var logger = runner_log.Logger.init(allocator, stderr_holder.sink());
var signal_guard = try runner_control.installSignalHandlers(); defer signal_guard.restore(); runner_control.reset();
const address = try parseSocketAddress(listen_address); var server = try address.listen(.{ .reuse_address = true }); defer server.deinit();
try logger.logf(.info, .{ .component = "distributed", .source = .host, .event = "agent_listening", }, "distributed agent listening on {s}", .{listen_address});
while (true) { var connection = try server.accept(); handleAcceptedConnection(allocator, &connection, stderr, &logger) catch |err| { try logger.logf(.err, .{ .component = "distributed", .source = .host, .event = "agent_request_failed", }, "agent request failed: {s}", .{@errorName(err)}); }; if (runner_control.loadStopRequested()) break; }
return if (runner_control.loadStopRequested()) .interrupted else .success;}
pub fn runDistributed( allocator: std.mem.Allocator, config_path: []const u8, agent_addresses: []const []const u8, wasm_backend_override: ?config.WasmBackend, stdout: anytype, stderr: anytype,) !contracts.ExitCode { var stderr_holder = runner_log.WriterHolder(@TypeOf(stderr)).init(stderr); var logger = runner_log.Logger.init(allocator, stderr_holder.sink());
if (agent_addresses.len == 0) { try logger.log(.err, "distributed run requires at least one --agent address", .{ .component = "distributed", .source = .host, .event = "missing_agent", }); return .invalid_config; }
var signal_guard = try runner_control.installSignalHandlers(); defer signal_guard.restore(); runner_control.reset();
var expanded = config.loadExpandedConfigSource(allocator, config_path, contracts.max_config_bytes) catch |err| { try logger.logf(.err, .{ .component = "distributed", .source = .host, .event = "config_error", }, "config {s}: {s}", .{ config.errorCategory(err), @errorName(err) }); return .invalid_config; }; defer expanded.deinit(allocator);
var scenario = config.ScenarioConfig.parseExpandedSourceWithEnv(allocator, expanded.source, &expanded.env_lookup) catch |err| { try logger.logf(.err, .{ .component = "distributed", .source = .host, .event = "config_error", }, "config {s}: {s}", .{ config.errorCategory(err), @errorName(err) }); return .invalid_config; }; defer scenario.deinit(); if (wasm_backend_override) |backend| scenario.scenario.wasm_backend = backend;
var setup_state = try prepareInitialStore(allocator, &scenario, &logger); defer setup_state.deinit();
const env_entries = try snapshotStringMap(allocator, &expanded.env_lookup); defer template.deinitSnapshotEntries(allocator, env_entries); const store_entries = try template.snapshot(allocator, &setup_state.shared_store); defer template.deinitSnapshotEntries(allocator, store_entries); var wasm_blob = try encodeOptionalFileBase64(allocator, scenario.scenario.wasm); defer wasm_blob.deinit(allocator); var ca_blob = try encodeOptionalFileBase64(allocator, scenario.http.defaults.tls.ca_file); defer ca_blob.deinit(allocator);
const active_agents = activeAgentCount(&scenario, agent_addresses.len); if (active_agents == 0) { try logger.log(.err, "distributed run produced no active shards", .{ .component = "distributed", .source = .host, .event = "no_active_shards", }); return .invalid_config; } if (active_agents < agent_addresses.len) { try logger.logf(.info, .{ .component = "distributed", .source = .host, .event = "agent_subset_used", }, "using {d} of {d} configured agents after shard partitioning", .{ active_agents, agent_addresses.len }); }
const invocations = try allocator.alloc(AgentInvocation, active_agents); defer allocator.free(invocations);
var started: usize = 0; errdefer { for (invocations[0..started]) |*invocation| invocation.join(); for (invocations[0..started]) |*invocation| if (invocation.response) |*response| response.deinit(allocator); }
const coordinator_unix_nanos = std.time.nanoTimestamp(); for (invocations, 0..) |*invocation, index| { invocation.* = .{ .allocator = allocator, .address = agent_addresses[index], .request = .{ .coordinator_unix_nanos = coordinator_unix_nanos, .expanded_config_source = expanded.source, .env = env_entries, .initial_store = store_entries, .shard_index = @intCast(index), .shard_count = @intCast(active_agents), .wasm_backend = if (scenario.scenario.wasm_backend == .wamr) "wamr" else "wasm3", .wasm_module_base64 = if (wasm_blob.base64) |bytes| bytes else null, .tls_ca_pem_base64 = if (ca_blob.base64) |bytes| bytes else null, }, }; try invocation.start(); started += 1; }
for (invocations[0..started]) |*invocation| invocation.join(); defer for (invocations[0..started]) |*invocation| if (invocation.response) |*response| response.deinit(allocator);
var merged = runner_metrics.MetricsAggregator{ .allocator = allocator }; defer merged.deinit(); var successful_agents: usize = 0;
for (invocations[0..started]) |*invocation| { if (invocation.err) |err| { try logger.logf(.warn, .{ .component = "distributed", .source = .host, .event = "agent_failed", }, "agent {s} failed: {s}; continuing with remaining agents", .{ invocation.address, @errorName(err) }); continue; }
const response = invocation.response orelse continue; if (!response.ok or response.snapshot == null) { try logger.logf(.warn, .{ .component = "distributed", .source = .host, .event = "agent_failed", }, "agent {s} returned failure: {s}; continuing with remaining agents", .{ invocation.address, response.error_message orelse "unknown agent error", }); continue; }
try logger.logf(.info, .{ .component = "distributed", .source = .host, .event = "agent_completed", }, "agent {s} completed shard={d} skew_ns={d}", .{ invocation.address, response.shard_index, response.clock_skew_nanos, }); try merged.mergeSnapshot(&response.snapshot.?); successful_agents += 1; }
if (setup_state.lifecycle) |*lifecycle| { if (try runner_orchestration.runWorkflowTeardown( lifecycle, &scenario, runner_control.loadStopRequested(), &logger, )) { return .invalid_config; } }
if (successful_agents == 0) return .invalid_config;
const interrupted = runner_control.loadStopRequested(); var snapshot = try merged.snapshot(allocator, interrupted); defer snapshot.deinit(allocator); var summary = try merged.finalize(allocator, &scenario, interrupted); defer summary.deinit();
runner_exporter.writeConfiguredObservation(allocator, &scenario, runner_observation.Observation.init(&summary, &snapshot), &logger) catch |err| { try logger.logf(.err, .{ .component = "exporter", .source = .host, .event = "export_failed", }, "exporter write failed: {s}", .{@errorName(err)}); }; try writeJsonLine(summary.output, stdout);
if (runner_control.loadStopRequested()) return .interrupted; if (summary.threshold_failed) return .threshold_failed; return .success;}
const PreparedSetupState = struct { session: runner_context.Session, lifecycle: ?workflow_scenario.ScenarioLifecycle = null, shared_store: template.VarStore,
fn deinit(self: *PreparedSetupState) void { if (self.lifecycle) |*lifecycle| lifecycle.deinit(); self.shared_store.deinit(); self.session.deinit(); self.* = undefined; }};
fn prepareInitialStore( allocator: std.mem.Allocator, scenario: *const config.ScenarioConfig, logger: *runner_log.Logger,) !PreparedSetupState { var session = try runner_context.Session.init(allocator, scenario); errdefer session.deinit();
var shared_store = template.VarStore.init(allocator); errdefer shared_store.deinit(); try shared_store.cloneFrom(&session.shared_store);
try runner_orchestration.runSetupPhase( allocator, &session.client, &shared_store, &session.tls_context, scenario, logger, );
var lifecycle: ?workflow_scenario.ScenarioLifecycle = null; errdefer if (lifecycle) |*value| value.deinit(); if (scenario.scenario.mode() == .workflow) { lifecycle = try runner_orchestration.runWorkflowSetup(allocator, &shared_store, scenario, logger); }
return .{ .session = session, .lifecycle = lifecycle, .shared_store = shared_store, };}
fn handleAcceptedConnection( allocator: std.mem.Allocator, connection: *std.net.Server.Connection, stderr: anytype, logger: *runner_log.Logger,) !void { defer connection.stream.close();
var read_buffer: [4096]u8 = undefined; var reader = connection.stream.reader(&read_buffer); reader = reader; const parsed = try readJsonFrame(allocator, reader.interface(), RunRequest); defer parsed.deinit();
var response = try handleRunRequest(allocator, parsed.value, stderr, logger); defer response.deinit(allocator);
var write_buffer: [4096]u8 = undefined; var writer = connection.stream.writer(&write_buffer); writer = writer; try writeJsonFrame(allocator, &writer.interface, response);}
fn handleRunRequest( allocator: std.mem.Allocator, request: RunRequest, stderr: anytype, logger: *runner_log.Logger,) !RunResponse { var env_lookup = try stringMapFromEntries(allocator, request.env); defer deinitStringMap(allocator, &env_lookup);
var scenario = config.ScenarioConfig.parseExpandedSourceWithEnv(allocator, request.expanded_config_source, &env_lookup) catch |err| { return .{ .shard_index = request.shard_index, .agent_unix_nanos = std.time.nanoTimestamp(), .clock_skew_nanos = std.time.nanoTimestamp() - request.coordinator_unix_nanos, .ok = false, .error_message = try std.fmt.allocPrint(allocator, "scenario parse failed: {s}", .{@errorName(err)}), }; }; defer scenario.deinit();
if (request.wasm_backend) |backend| { scenario.scenario.wasm_backend = parseWasmBackendLabel(backend) catch scenario.scenario.wasm_backend; }
var files = try materializeAgentFiles(allocator, request); defer files.deinit(allocator); if (files.wasm_path) |path| scenario.scenario.wasm = path; if (files.ca_file_path) |path| scenario.http.defaults.tls.ca_file = path;
applyShardToScenario(&scenario, request.shard_index, request.shard_count);
var initial_store = template.VarStore.init(allocator); defer initial_store.deinit(); try template.applySnapshot(&initial_store, request.initial_store);
var result = runner_entry.execute(allocator, &scenario, stderr, .{ .initial_store = &initial_store, .run_setup = false, .run_workflow_setup = false, .run_workflow_teardown = false, .write_exporters = false, .abort_on_fail_enabled = false, .evaluate_thresholds = false, }) catch |err| { return .{ .shard_index = request.shard_index, .agent_unix_nanos = std.time.nanoTimestamp(), .clock_skew_nanos = std.time.nanoTimestamp() - request.coordinator_unix_nanos, .ok = false, .error_message = try std.fmt.allocPrint(allocator, "run failed: {s}", .{@errorName(err)}), }; }; defer result.deinit();
try logger.logf(.info, .{ .component = "distributed", .source = .host, .event = "agent_shard_finished", }, "finished shard={d} exit_code={d}", .{ request.shard_index, result.exit_code.code() });
return .{ .shard_index = request.shard_index, .agent_unix_nanos = std.time.nanoTimestamp(), .clock_skew_nanos = std.time.nanoTimestamp() - request.coordinator_unix_nanos, .ok = true, .exit_code = result.exit_code.code(), .snapshot = try cloneSnapshot(allocator, result.snapshot), };}
fn parseSocketAddress(raw: []const u8) !std.net.Address { const colon = std.mem.lastIndexOfScalar(u8, raw, ':') orelse return error.InvalidAddress; const host = raw[0..colon]; const port = try std.fmt.parseInt(u16, raw[colon + 1 ..], 10); return std.net.Address.parseIp(host, port);}
fn writeJsonFrame(allocator: std.mem.Allocator, writer: anytype, value: anytype) !void { var out: std.Io.Writer.Allocating = .init(allocator); defer out.deinit(); try std.json.Stringify.value(value, .{}, &out.writer);
var length_bytes: [8]u8 = undefined; std.mem.writeInt(u64, &length_bytes, @intCast(out.writer.buffered().len), .little); try writer.writeAll(&length_bytes); try writer.writeAll(out.writer.buffered());}
fn readJsonFrame(allocator: std.mem.Allocator, reader: anytype, comptime T: type) !std.json.Parsed(T) { var length_bytes: [8]u8 = undefined; try reader.readSliceAll(&length_bytes); const payload_len = std.mem.readInt(u64, &length_bytes, .little); const payload = try allocator.alloc(u8, payload_len); defer allocator.free(payload); try reader.readSliceAll(payload); return std.json.parseFromSlice(T, allocator, payload, .{});}
fn sendRunRequest(allocator: std.mem.Allocator, address_text: []const u8, request: *const RunRequest) !RunResponse { const address = try parseSocketAddress(address_text); var stream = try std.net.tcpConnectToAddress(address); defer stream.close();
var write_buffer: [4096]u8 = undefined; var writer = stream.writer(&write_buffer); writer = writer; try writeJsonFrame(allocator, &writer.interface, request.*);
var read_buffer: [4096]u8 = undefined; var reader = stream.reader(&read_buffer); reader = reader; var parsed = try readJsonFrame(allocator, reader.interface(), RunResponse); defer parsed.deinit();
var response = parsed.value; if (response.error_message) |message| { response.error_message = try allocator.dupe(u8, message); } if (response.snapshot) |snapshot| { response.snapshot = try cloneSnapshot(allocator, snapshot); } return response;}
fn cloneSnapshot(allocator: std.mem.Allocator, snapshot: runner_metrics.AggregatorSnapshot) !runner_metrics.AggregatorSnapshot { var aggregator = runner_metrics.MetricsAggregator{ .allocator = allocator }; defer aggregator.deinit(); try aggregator.mergeSnapshot(&snapshot); return aggregator.snapshot(allocator, snapshot.interrupted);}
fn stringMapFromEntries(allocator: std.mem.Allocator, entries: []const KeyValueEntry) !std.StringHashMapUnmanaged([]const u8) { var map: std.StringHashMapUnmanaged([]const u8) = .empty; errdefer deinitStringMap(allocator, &map); for (entries) |entry| { const owned_key = try allocator.dupe(u8, entry.key); errdefer allocator.free(owned_key); const owned_value = try allocator.dupe(u8, entry.value); errdefer allocator.free(owned_value); try map.put(allocator, owned_key, owned_value); } return map;}
fn deinitStringMap(allocator: std.mem.Allocator, map: *std.StringHashMapUnmanaged([]const u8)) void { var iterator = map.iterator(); while (iterator.next()) |entry| { allocator.free(entry.key_ptr.*); allocator.free(entry.value_ptr.*); } map.deinit(allocator);}
fn snapshotStringMap(allocator: std.mem.Allocator, map: *const std.StringHashMapUnmanaged([]const u8)) ![]KeyValueEntry { var entries = std.ArrayList(KeyValueEntry).empty; errdefer { for (entries.items) |entry| { allocator.free(entry.key); allocator.free(entry.value); } entries.deinit(allocator); }
var iterator = map.iterator(); while (iterator.next()) |entry| { try entries.append(allocator, .{ .key = try allocator.dupe(u8, entry.key_ptr.*), .value = try allocator.dupe(u8, entry.value_ptr.*), }); }
std.sort.block(KeyValueEntry, entries.items, {}, struct { fn lessThan(_: void, left: KeyValueEntry, right: KeyValueEntry) bool { return std.mem.lessThan(u8, left.key, right.key); } }.lessThan); return try entries.toOwnedSlice(allocator);}
fn encodeOptionalFileBase64(allocator: std.mem.Allocator, path: ?[]const u8) !FileBlob { const raw_path = path orelse return .{}; const file_bytes = try std.fs.cwd().readFileAlloc(allocator, raw_path, 32 * 1024 * 1024); defer allocator.free(file_bytes);
const encoded_len = std.base64.standard.Encoder.calcSize(file_bytes.len); const encoded = try allocator.alloc(u8, encoded_len); _ = std.base64.standard.Encoder.encode(encoded, file_bytes); return .{ .base64 = encoded };}
fn materializeAgentFiles(allocator: std.mem.Allocator, request: RunRequest) !MaterializedFiles { try std.fs.cwd().makePath(".zig-cache/distributed-agent");
return .{ .wasm_path = try materializeBase64File(allocator, request.wasm_module_base64, "scenario", ".wasm"), .ca_file_path = try materializeBase64File(allocator, request.tls_ca_pem_base64, "ca", ".pem"), };}
fn materializeBase64File( allocator: std.mem.Allocator, base64: ?[]const u8, prefix: []const u8, extension: []const u8,) !?[]u8 { const encoded = base64 orelse return null; const decoded_len = try std.base64.standard.Decoder.calcSizeForSlice(encoded); const decoded = try allocator.alloc(u8, decoded_len); defer allocator.free(decoded); try std.base64.standard.Decoder.decode(decoded, encoded);
const path = try std.fmt.allocPrint(allocator, ".zig-cache/distributed-agent/{s}-{d}{s}", .{ prefix, @as(u64, @intCast(@max(std.time.nanoTimestamp(), 0))), extension, }); errdefer allocator.free(path); try std.fs.cwd().writeFile(.{ .sub_path = path, .data = decoded }); return path;}
fn activeAgentCount(scenario: *const config.ScenarioConfig, available_agents: usize) usize { const desired: u32 = switch (scenario.execution.mode) { .constant_vus => scenario.execution.vus.?, .constant_arrival_rate => @min(@min(scenario.execution.rate.?, scenario.execution.pre_allocated_vus.?), scenario.execution.max_vus.?), .ramping_vus => scenario.execution.maxRampingVus(), }; return @max(@as(usize, 1), @min(@as(usize, desired), available_agents));}
fn applyShardToScenario(scenario: *config.ScenarioConfig, shard_index: u32, shard_count: u32) void { switch (scenario.execution.mode) { .constant_vus => scenario.execution.vus = partitionCount(scenario.execution.vus.?, shard_index, shard_count), .constant_arrival_rate => { scenario.execution.rate = partitionCount(scenario.execution.rate.?, shard_index, shard_count); scenario.execution.pre_allocated_vus = partitionCount(scenario.execution.pre_allocated_vus.?, shard_index, shard_count); scenario.execution.max_vus = partitionCount(scenario.execution.max_vus.?, shard_index, shard_count); }, .ramping_vus => { for (@constCast(scenario.execution.stages)) |*stage| { stage.target_vus = partitionCount(stage.target_vus, shard_index, shard_count); } }, }}
fn partitionCount(total: u32, shard_index: u32, shard_count: u32) u32 { const base = @divTrunc(total, shard_count); const remainder = @mod(total, shard_count); return base + @as(u32, if (shard_index < remainder) 1 else 0);}
fn parseWasmBackendLabel(raw: []const u8) error{InvalidWasmBackend}!config.WasmBackend { if (std.mem.eql(u8, raw, "wamr")) return .wamr; if (std.mem.eql(u8, raw, "wasm3")) return .wasm3; return error.InvalidWasmBackend;}
fn writeJsonLine(value: anytype, stdout: anytype) !void { if (@typeInfo(@TypeOf(stdout)) == .pointer) { try std.json.Stringify.value(value, .{}, stdout); try stdout.writeAll("\n"); try stdout.flush(); return; }
var writer = stdout; var adapter_buffer: [256]u8 = undefined; var adapter = writer.adaptToNewApi(&adapter_buffer); try std.json.Stringify.value(value, .{}, &adapter.new_interface); try adapter.new_interface.writeAll("\n"); try adapter.new_interface.flush();}
test "partition count keeps totals balanced" { try std.testing.expectEqual(@as(u32, 2), partitionCount(5, 0, 3)); try std.testing.expectEqual(@as(u32, 2), partitionCount(5, 1, 3)); try std.testing.expectEqual(@as(u32, 1), partitionCount(5, 2, 3));}
test "apply shard repartitions constant arrival fields consistently" { var scenario = config.ScenarioConfig{ .arena = undefined, .scenario = .{ .name = "arrival", .protocol = .http, .target = "http://127.0.0.1:18080", }, .execution = .{ .mode = .constant_arrival_rate, .duration = config.Duration.fromSeconds(1), .rate = 10, .pre_allocated_vus = 7, .max_vus = 13, }, .setup = .{ .requests = &.{} }, .http = .{ .defaults = .{}, .requests = &.{} }, .thresholds = &.{}, };
applyShardToScenario(&scenario, 1, 3);
try std.testing.expectEqual(@as(u32, 3), scenario.execution.rate.?); try std.testing.expectEqual(@as(u32, 2), scenario.execution.pre_allocated_vus.?); try std.testing.expectEqual(@as(u32, 4), scenario.execution.max_vus.?);}
test "apply shard repartitions ramp stages in place" { var stages = [_]config.RampStage{ .{ .target_vus = 5, .duration = config.Duration.fromSeconds(1) }, .{ .target_vus = 8, .duration = config.Duration.fromSeconds(2) }, }; var scenario = config.ScenarioConfig{ .arena = undefined, .scenario = .{ .name = "ramping", .protocol = .http, .target = "http://127.0.0.1:18080", }, .execution = .{ .mode = .ramping_vus, .duration = config.Duration.fromSeconds(3), .stages = stages[0..], }, .setup = .{ .requests = &.{} }, .http = .{ .defaults = .{}, .requests = &.{} }, .thresholds = &.{}, };
applyShardToScenario(&scenario, 1, 3);
try std.testing.expectEqual(@as(u32, 2), scenario.execution.stages[0].target_vus); try std.testing.expectEqual(@as(u32, 3), scenario.execution.stages[1].target_vus);}
test "active agent count is bounded by requested load and available agents" { const scenario = config.ScenarioConfig{ .arena = undefined, .scenario = .{ .name = "bounded", .protocol = .http, .target = "http://127.0.0.1:18080", }, .execution = .{ .mode = .constant_vus, .duration = config.Duration.fromSeconds(1), .vus = 2, }, .setup = .{ .requests = &.{} }, .http = .{ .defaults = .{}, .requests = &.{} }, .thresholds = &.{}, };
try std.testing.expectEqual(@as(usize, 1), activeAgentCount(&scenario, 1)); try std.testing.expectEqual(@as(usize, 2), activeAgentCount(&scenario, 4));}