Compare commits

...

19 Commits

Author SHA1 Message Date
mikkeli 7ca74366a3 Merge branch 'fix/release-build-jni-keep-rules'
CI / Analyze & Test (push) Failing after 30s
Release builds aborted on the first callback of every test: R8 renamed the
IperfCallback implementation and its methods, so the JNI GetMethodID lookups
resolved nothing. Adds the keep rules, and makes the native side report a
failed lookup instead of aborting the process on the next JNI call.

Debug builds do not minify, so every on-device check until now passed while the
shipping artifact was broken. Found by running the release APK during release
preparation.

Verified with the release APK on an XQ-AS72: clean run at 806 Mbits/sec,
matching the server's own figure.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 22:43:52 +09:00
mikkeli ff13d63333 fix(jni): fail cleanly when a callback method does not resolve
GetMethodID raises NoSuchMethodError when a lookup fails, and any further JNI
call made while an exception is pending aborts the process. runIperfLive
resolved three method IDs back to back without checking, so the first failure
made the second call fatal — turning a diagnosable configuration problem into
a SIGABRT with a stack that pointed at the JNI entry rather than the cause.

resolve_method() clears the pending exception and returns NULL, and the caller
now bails out with a log naming which lookups failed and pointing at the keep
rules. The R8 problem this exposed is fixed separately; this is about the
failure being reportable rather than fatal, whatever the cause.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 22:43:35 +09:00
mikkeli 2b3f20d3a0 fix(android): keep the JNI callback names through R8
Release builds aborted on the first callback of every test:

  NoSuchMethodError: no non-static method "Lp0;.onOutput(Ljava/lang/String;)V"

R8 had renamed MainThreadCallback to p0 along with its methods, so
GetMethodID(env, cls, "onOutput", ...) in iperf_jni.c resolved nothing. The
names are a contract between C and Kotlin that the minifier cannot see.

Adds keep rules for IperfRunner, the IperfCallback interface and — the part
that matters — everything implementing it, since the lookup happens on the
concrete object's class rather than on the interface. A general rule keeps any
class declaring a native method, so a future one is covered without a new rule.

Debug builds do not minify, which is why every on-device check so far passed
while the shipping artifact was broken. Found by running the release APK
during release preparation.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 22:43:35 +09:00
mikkeli 894712b7a8 chore: set version to 0.1.0 for the first release
pubspec.yaml still carried flutter create's placeholder 1.0.0+1, which would
have had the APK reporting 1.0.0 while the release was tagged v0.1.0. Matches
the version the tag records.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 22:38:48 +09:00
mikkeli 895b963745 fix: restore speedtest.uztelecom.uz as the default server
Consolidating the UI's seed values onto TestConfiguration's own defaults also
silently changed the default target to iperf.es.net, which was not asked for.
Sets it back in TestConfiguration, which is now the single definition the
screen and the headless entry point both read.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 22:38:19 +09:00
mikkeli b76098c7e6 Merge branch 'refactor/core-independent-of-ui'
CI / Analyze & Test (push) Failing after 30s
Make the core work independently of the UI: Iperf3Session accumulates a run in
the domain layer, so the view model holds no run data and the screen derives no
numbers. Replacing the presentation layer now means rewriting rendering, not
re-deriving results.

Adds lib/main_headless.dart, which runs a full test through Iperf3Service and
Iperf3Session with no widget tree, as a standing check on that claim — and as
the accurate way to measure: 30.2% local CPU headless against 79.9% through the
UI on a comparable 4-stream run.

Verified on an XQ-AS72: headless run clean at 859 Mbit/s mean, matching the
server's own 859 Mbits/sec receiver figure.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 20:25:24 +09:00
mikkeli 6e35d724dc docs: record that the core runs without the UI, and the CPU cost of the UI
States where run data lives now that Iperf3Session owns it, so the next person
does not put accumulation back in the view model, and documents the headless
entry point as the way to check that claim rather than trust it.

Includes the measurement that motivates using it: 30.2% local CPU headless
versus 79.9% through the UI on a comparable 4-stream run. That gap is worth
recording, because it means throughput read off the app's own screen is
pessimistic at high rates and should not be compared against a headless or
desktop figure without noting which path produced it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 20:25:06 +09:00
mikkeli fc15897541 feat: add a headless entry point that runs a test with no UI
Separation that nothing exercises is separation that quietly stops being true,
so this runs a full test through Iperf3Service and Iperf3Session with
WidgetsFlutterBinding but no runApp: no widget tree, no render surface. If the
run path ever starts needing the UI, this stops working. An architecture test
additionally forbids it importing lib/ui.

It is also the accurate way to measure. A 4-stream run against a local server
reports 30.2% local CPU here, against 79.9% for a comparable run with the
transcript repainting alongside — the UI was costing roughly fifty points of
CPU on a phone already near CPU-bound at gigabit rates. Throughput figures
taken through the UI are therefore pessimistic, and this is the path to use
when the number matters.

Parameters come from --dart-define so a run needs no code edit:
  flutter run -t lib/main_headless.dart --dart-define=IPERF_SERVER=…

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 20:24:44 +09:00
mikkeli 9485049b57 refactor: move run accumulation out of the view model into the domain
The view model was doing two jobs. Alongside presentation state it held what
happened during a run — the interval series, the rule that iperf3's omitted
warm-up intervals do not count, the retained end summary — and the screen
computed mean and peak inline in a widget builder. All of that is the part
that has to be correct, and all of it would have been rewritten by anyone
replacing the UI.

Iperf3Session accumulates a run in the domain layer: samples, totals, errors,
whether it was stopped, and the statistics over them. The view model now feeds
it events and keeps only a formatted transcript and the repaint schedule; the
screen reads every displayed number off the session and derives none.

Two details the session now owns rather than leaving to a caller. Omitted
intervals are excluded, so a warm-up cannot drag the mean down. And
totalRetransmits stays null when no interval reported a count — UDP does not
measure retransmits, and "not measured" must not render as zero.

The aggregation tests move with the logic, into a pure-Dart test with no
widgets or bindings involved.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 20:24:44 +09:00
mikkeli 838c883cc0 Merge branch 'refactor/separate-ui-from-data'
CI / Analyze & Test (push) Failing after 38s
Separate presentation from the data layer: the UI depends on an Iperf3Runner
interface declared in the domain layer, and main.dart is the only file that
names a concrete implementation.

Adds widget tests that drive the real UI against an in-memory runner with no
MethodChannel or native library, and an architecture test that reads the
imports under lib/ and fails the build when a layer boundary is crossed.

Verified on an XQ-AS72 after the change: clean run, iperf_run_client returned
0, server logged 608 Mbits/sec, no ANR or native abort.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 19:56:41 +09:00
mikkeli fe042efc29 docs: record the layering rule and where it is enforced
The architecture section listed files but said nothing about which layer may
import what, so the direction of dependency was only visible by reading the
imports. States the rule as a table, notes that the UI depends on the
Iperf3Runner contract rather than on a transport and what that buys, and points
at the test that enforces it so the rule is not just prose.

Also brings the tree up to date: it was missing the domain services directory,
the event model and the formatter.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 19:56:25 +09:00
mikkeli 0cf019379a test: fail the build when a layer boundary is crossed
The layering only holds if something checks it, so these tests read the real
import statements under lib/ and assert the direction: domain imports no
Flutter and nothing else in the package, data never reaches into ui and may
import flutter/services alone, and ui never names a concrete transport.

A final test asserts the set of directories under lib/ is exactly the three
layers, so a new one cannot appear and silently escape every rule above.

Each violation reports the offending file and import with the reason, since a
guard that only says "expected empty" costs more than it saves. Verified by
introducing a UI-to-data import and a Flutter import in domain and confirming
both fail.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 19:56:03 +09:00
mikkeli 95acf5ea38 test: drive the real UI against an in-memory runner
FakeIperf3Runner implements Iperf3Runner, so the widget tests exercise the
actual widget tree — GO, STOP, the status line, the stat row, validation —
with no MethodChannel and no native library. That was impossible while the
screen constructed its own Iperf3Service.

The view model tests share the same fake instead of each file carrying a
double that had to mirror the concrete service.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 19:56:03 +09:00
mikkeli 314a3ea059 refactor: depend on an Iperf3Runner interface instead of the service
The presentation layer imported Iperf3Service directly, so the UI was welded
to the MethodChannel transport: the view model named it, and the screen
constructed one. Dependency direction was already inward-only, but the UI
depended on an implementation rather than a contract.

Iperf3Runner states that contract in the domain layer in five members, in pure
Dart with no Flutter import, and Iperf3Service implements it. The view model
and screen now take an Iperf3Runner; main.dart is the only file that names a
concrete one, which makes it the composition root.

Two consequences worth having. The UI can be driven against an in-memory
runner with no MethodChannel, native library or device involved. And a test
double implements five stable members rather than tracking every public member
the transport happens to expose — the previous double, forced to implement the
concrete class, broke twice while this branch's work was going on.

Also drops flutter/foundation from the data layer: debugPrint gives way to
dart:developer, leaving flutter/services (where MethodChannel lives) as that
layer's only Flutter dependency.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 19:56:03 +09:00
mikkeli defd64a073 Merge branch 'refactor/json-stream-events'
CI / Analyze & Test (push) Failing after 34s
Replace the stdout pipe with iperf3's json_callback hook and consume the
resulting --json-stream events as structured data: interval samples with
retransmits and per-stream detail, and an end summary with sent/received
totals and CPU utilisation.

Deletes the pipe, the reader thread and the join-ordering and ownership
constraints that came with them.

Verified on an XQ-AS72 against a local iperf3 server: 4 streams at 889
Mbits/sec, matching the server's own 887 Mbits/sec receiver figure. Across
four consecutive runs thread count returned to baseline and fd count returned
exactly to baseline, with no ANR or native abort.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 19:35:55 +09:00
mikkeli 857b79fbaf docs: replace the pipe design with json_callback and note the embedding costs
The output-streaming section described the pipe and reader thread that no
longer exist, including the join-ordering rule that was the reason they were
dangerous. Replaced with how the json_callback path works and why, and an
explicit note not to reintroduce the pipe.

Adds a section on what embedding a CLI in a long-lived app process actually
costs, since that is the recurring trap here: iperf3's main() can leave
process-global state behind because it is about to exit, and this app cannot.
Records what iperf3 does clean up — joined stream threads, closed fds, an
immediately unlinked temp file — with the measurements taken on device, so the
next person does not have to re-derive whether repeated runs leak.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 19:35:41 +09:00
mikkeli cbb2aba8b0 feat(ui): render the event stream and show live throughput figures
Consuming JSON means the familiar iperf3 text layout has to be rebuilt, so a
pure formatter turns each event back into a line — binary units for transfer
totals, decimal units for bitrates, matching how iperf3 quotes each. The view
model keeps the interval series and the end summary as data alongside the
transcript, and a stat row shows current/total, mean, peak and sample count
off that series. A chart can be driven from the same list without re-parsing
text.

Repaints are coalesced on a 250ms timer rather than one per event. Reports can
now arrive several times a second across many streams, and each rebuild
re-renders the whole transcript, so notifying per event made the cost of
drawing scale with the report rate — which competes with the test itself for
CPU and skews the measurement.

Warm-up intervals (-O) are marked omitted by iperf3 and are kept out of the
series so they cannot drag the mean down.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 19:35:10 +09:00
mikkeli 7d8d06e2e5 feat(app): parse json-stream reports into structured events
The native layer now emits one JSON object per report, so the service parses
each into a sealed Iperf3Event — start, interval, end, error — and publishes
those instead of opaque lines. Interval samples carry bytes, bits per second,
retransmits and per-stream socket/cwnd/rtt detail; the end event carries sent
and received totals and CPU utilisation. None of that was available while the
output was scraped text.

Anything unrecognised — non-JSON, malformed JSON, an event name a future
iperf3 adds — becomes an Iperf3LogLine rather than being dropped, so
unexpected output still reaches the user.

Failures arrive as an `error` event rather than a non-zero return from
iperf_run_client, so that event is what now marks a run as failed. The
result's rawOutput keeps the JSON lines verbatim, since that is what the
native layer actually produced.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 19:35:10 +09:00
mikkeli 598a2d99c9 refactor(jni): take results from json_callback instead of piping stdout
iperf3 exposes a hook for exactly this use — iperf.h describes json_callback
as "allow user apps to receive the JSON strings, instead of writing them to
the output file". Setting it alongside --json-stream's two flags makes iperf3
hand each report ("start", "interval", "end", "error") straight to the bridge
as a JSON string, and test->outfile is never touched.

That removes the pipe, the reader thread, the fdopen/fgets loop, and
AttachCurrentThread from the output path — roughly 90 lines. It also removes
the two constraints that came with them and were both gotten wrong: that the
write end must be closed before joining a reader blocked in fgets(), and that
exactly one side may own the shared state struct. Neither can be violated now
because neither exists.

json_callback carries no user-data pointer, so the run state is reached
through a global published before iperf_run_client() and cleared after it.
Only one test runs at a time, which runIperfLive already enforced. The
callback fires on iperf3's reporting thread, so it resolves a JNIEnv for the
calling thread rather than trusting a stored one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 19:35:10 +09:00
22 changed files with 1700 additions and 327 deletions
+7
View File
@@ -37,6 +37,13 @@ android {
// TODO: Add your own signing config for the release build. // TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works. // Signing with the debug keys for now, so `flutter run --release` works.
signingConfig = signingConfigs.getByName("debug") signingConfig = signingConfigs.getByName("debug")
// proguard-rules.pro keeps the names JNI resolves at runtime.
// Without it a release build aborts on the first callback.
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro",
)
} }
} }
+21
View File
@@ -0,0 +1,21 @@
# JNI reaches these by name. R8 renames by default, so without these rules a
# release build resolves nothing: GetMethodID("onOutput", ...) returns NULL,
# raises NoSuchMethodError, and the next JNI call aborts the process with
# NoSuchMethodError: no non-static method "Lp0;.onOutput(Ljava/lang/String;)V"
# Debug builds do not minify, so this only ever appears in release.
# The plugin object holds the native method declarations and is looked up from
# C by its fully qualified name (Java_com_novoyuuparosk_iperf3gui_IperfRunner_*).
-keep class com.novoyuuparosk.iperf3gui.IperfRunner { *; }
# The callback interface and everything implementing it: iperf_jni.c resolves
# onOutput/onError/onComplete by name on the concrete object's class, so the
# implementors' method names must survive too, not just the interface's.
-keep interface com.novoyuuparosk.iperf3gui.IperfRunner$IperfCallback { *; }
-keep class * implements com.novoyuuparosk.iperf3gui.IperfRunner$IperfCallback { *; }
# Belt and braces for any future native method: keep the name of any class
# declaring one, and the native methods themselves.
-keepclasseswithmembernames,includedescriptorclasses class * {
native <methods>;
}
+97 -156
View File
@@ -5,16 +5,25 @@
* the Flutter app to run iperf3 tests natively inside the app process * the Flutter app to run iperf3 tests natively inside the app process
* (no Process.start needed, no SELinux restrictions). * (no Process.start needed, no SELinux restrictions).
* *
* OUTPUT NOTE:
* The test runs in --json-stream mode with a json_callback installed, so
* iperf3 hands each event ("start", "interval", "end", "error") straight to
* us as a JSON string and never touches test->outfile. That is what the hook
* exists for -- iperf.h calls it "allow user apps to receive the JSON
* strings, instead of writing them to the output file".
*
* An earlier version piped test->outfile to a reader thread instead. That
* required closing the pipe's write end before joining the reader (which
* blocks in fgets() until EOF) and single ownership of the shared state
* struct. Both were gotten wrong and deadlocked every test. Reading events
* from the callback removes the pipe, the reader thread, and that whole class
* of ordering bug.
*
* THREADING NOTE: * THREADING NOTE:
* runIperfLive() BLOCKS for the whole duration of the test. Kotlin must * runIperfLive() BLOCKS for the whole duration of the test. Kotlin must
* call it from a worker thread, never from the Flutter platform thread. * call it from a worker thread, never from the Flutter platform thread.
* * json_callback fires on whichever thread iperf3 reports from, so it resolves
* PIPE / SHUTDOWN NOTE: * a JNIEnv for the calling thread rather than reusing a stored one.
* iperf's output goes to a pipe drained by a reader thread that blocks in
* fgets(). The reader only sees EOF once the write end is closed, so the
* write end MUST be closed before pthread_join() — joining first deadlocks.
* The state struct is owned solely by the JNI caller, which frees it after
* joining the reader; the reader must never free it.
* *
* SIGNAL HANDLING NOTE: * SIGNAL HANDLING NOTE:
* iperf3's run() function (called from iperf_run_client()) uses * iperf3's run() function (called from iperf_run_client()) uses
@@ -61,21 +70,37 @@ static pthread_mutex_t g_test_mutex = PTHREAD_MUTEX_INITIALIZER;
static volatile int g_stop = 0; static volatile int g_stop = 0;
static char g_tmp_template[1024] = "/data/local/tmp/iperf3.XXXXXX"; static char g_tmp_template[1024] = "/data/local/tmp/iperf3.XXXXXX";
/* Per-call state shared between the JNI caller and the reader thread. /* Per-call state, reachable from the json_callback.
* We store the callback object (global ref) and method IDs.
* Callbacks are invoked via CallVoidMethod, NOT as function pointers. */ * Callbacks are invoked via CallVoidMethod, NOT as function pointers. */
struct iperf_run_state { struct iperf_run_state {
jobject callback_ref; /* Global ref to the callback object */ jobject callback_ref; /* Global ref to the callback object */
jmethodID mid_output; /* Method ID for onOutput(String) */ jmethodID mid_output; /* Method ID for onOutput(String) */
jmethodID mid_error; /* Method ID for onError(String) */ jmethodID mid_error; /* Method ID for onError(String) */
jmethodID mid_complete; /* Method ID for onComplete() */ jmethodID mid_complete; /* Method ID for onComplete() */
FILE *outfile; /* Pipe write end; NULL once closed */
int pipe_fd[2];
JavaVM *jvm; JavaVM *jvm;
pthread_t reader_thread;
int reader_started; /* Only join if pthread_create succeeded */
}; };
/* iperf3's json_callback signature carries no user-data pointer, so the
* current run's state has to be reachable from a global. Only one test runs
* at a time (enforced in runIperfLive), and this is published before
* iperf_run_client() and cleared after it returns. */
static struct iperf_run_state *g_current_state = NULL;
/* Resolve a method ID, clearing the exception a failed lookup leaves behind.
*
* GetMethodID raises NoSuchMethodError on failure, and any further JNI call
* made while an exception is pending aborts the process. Returning NULL and
* clearing lets the caller fail on its own terms. */
static jmethodID resolve_method(JNIEnv *env, jclass cls,
const char *name, const char *sig) {
jmethodID mid = (*env)->GetMethodID(env, cls, name, sig);
if ((*env)->ExceptionCheck(env)) {
(*env)->ExceptionClear(env);
return NULL;
}
return mid;
}
/* Helper: invoke the output callback via CallVoidMethod */ /* Helper: invoke the output callback via CallVoidMethod */
static void signal_output(JNIEnv *env, struct iperf_run_state *state, static void signal_output(JNIEnv *env, struct iperf_run_state *state,
const char *msg) { const char *msg) {
@@ -108,50 +133,36 @@ static void signal_complete(JNIEnv *env, struct iperf_run_state *state) {
} }
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
/* Output reader thread — reads from iperf's output pipe and forwards */ /* json_callback — receives one JSON event string per report from */
/* each line to the Java callback via JNI. */ /* iperf3 and forwards it to Java verbatim. Parsing happens in Dart. */
/* */ /* */
/* Exits when the write end of the pipe is closed (EOF). Does NOT own */ /* Runs on iperf3's reporting thread. In the client that is the thread */
/* `state`: the JNI caller frees it after joining this thread. */ /* that called iperf_run_client() (already attached, since Kotlin's */
/* executor thread is a Java thread), but GetEnv is checked rather */
/* than assumed, with an attach as fallback. */
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
static void *reader_thread_func(void *arg) { static void json_event_callback(struct iperf_test *test, char *json) {
struct iperf_run_state *state = (struct iperf_run_state *) arg; struct iperf_run_state *state = g_current_state;
JNIEnv *env; if (!state || !json) return;
int ret;
/* Attach this native thread to the Java VM */ JNIEnv *env = NULL;
ret = (*state->jvm)->AttachCurrentThread(state->jvm, &env, NULL); int attached = 0;
if (ret != JNI_OK) {
LOGE("AttachCurrentThread failed: %d", ret); if ((*state->jvm)->GetEnv(state->jvm, (void **) &env, JNI_VERSION_1_6)
/* Still drain the pipe so writers never block on a full pipe. */ != JNI_OK) {
char drain[1024]; if ((*state->jvm)->AttachCurrentThread(state->jvm, &env, NULL)
while (read(state->pipe_fd[0], drain, sizeof(drain)) > 0) { } != JNI_OK) {
close(state->pipe_fd[0]); LOGE("json_event_callback: could not reach a JNIEnv");
return NULL; return;
}
attached = 1;
} }
char buf[1024]; signal_output(env, state, json);
FILE *fp = fdopen(state->pipe_fd[0], "r");
if (fp) {
while (fgets(buf, sizeof(buf), fp) != NULL) {
/* Skip empty lines */
if (buf[0] == '\n' || buf[0] == '\0')
continue;
jstring line = (*env)->NewStringUTF(env, buf);
if (line != NULL) {
(*env)->CallVoidMethod(env, state->callback_ref,
state->mid_output, line);
(*env)->DeleteLocalRef(env, line);
}
}
fclose(fp); /* also closes pipe_fd[0] */
} else {
close(state->pipe_fd[0]);
}
/* Detach this native thread */ if (attached) {
(*state->jvm)->DetachCurrentThread(state->jvm); (*state->jvm)->DetachCurrentThread(state->jvm);
return NULL; }
} }
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
@@ -198,30 +209,12 @@ static void free_argv(char **argv, int argc) {
free(argv); free(argv);
} }
/* ------------------------------------------------------------------ */
/* Close the pipe write end. Idempotent — both the normal and the */
/* longjmp path call it, and the second call must be a no-op. */
/* */
/* Closing this is what makes the reader thread see EOF and exit, so */
/* it must happen before any pthread_join(). */
/* ------------------------------------------------------------------ */
static void close_outfile(struct iperf_run_state *state) {
if (state && state->outfile) {
fflush(state->outfile);
fclose(state->outfile);
state->outfile = NULL;
}
}
/* Retire the global test pointer and free it, under the mutex. */ /* Retire the global test pointer and free it, under the mutex. */
static void retire_test(void) { static void retire_test(void) {
pthread_mutex_lock(&g_test_mutex); pthread_mutex_lock(&g_test_mutex);
struct iperf_test *test = g_test; struct iperf_test *test = g_test;
g_test = NULL; g_test = NULL;
if (test) { if (test) {
/* outfile is a closed FILE* by now — point it somewhere harmless so
* nothing in the teardown path can write to a dead stream. */
test->outfile = stdout;
iperf_free_test(test); iperf_free_test(test);
} }
pthread_mutex_unlock(&g_test_mutex); pthread_mutex_unlock(&g_test_mutex);
@@ -236,14 +229,8 @@ static void iperf_cleanup_and_signal(JNIEnv *env,
struct iperf_run_state *state, struct iperf_run_state *state,
char **argv, int argc, char **argv, int argc,
int ret, int stopped) { int ret, int stopped) {
/* Close the write end FIRST: the reader thread is blocked in fgets() /* No more events can be delivered once the run is over. */
* and only unblocks on EOF. Joining before this would deadlock. */ g_current_state = NULL;
close_outfile(state);
if (state->reader_started) {
pthread_join(state->reader_thread, NULL);
state->reader_started = 0;
}
/* Restore default signal handlers before g_sigend_jmp_buf goes stale. */ /* Restore default signal handlers before g_sigend_jmp_buf goes stale. */
iperf_catch_sigend(SIG_DFL); iperf_catch_sigend(SIG_DFL);
@@ -259,15 +246,11 @@ static void iperf_cleanup_and_signal(JNIEnv *env,
/* Signal result to Java */ /* Signal result to Java */
if (user_stopped) { if (user_stopped) {
signal_output(env, state, "[iPerf JNI] Test was stopped by user.\n"); signal_output(env, state, "{\"event\":\"jni_stopped\",\"data\":{}}");
} else if (ret < 0) { } else if (ret < 0) {
char errbuf[256]; char errbuf[256];
snprintf(errbuf, sizeof(errbuf), snprintf(errbuf, sizeof(errbuf), "%s", iperf_strerror(i_errno));
"[iPerf JNI] Test failed: %s\n",
iperf_strerror(i_errno));
signal_error(env, state, errbuf); signal_error(env, state, errbuf);
} else {
signal_output(env, state, "[iPerf JNI] Test completed successfully.\n");
} }
/* Signal completion to Java */ /* Signal completion to Java */
@@ -304,13 +287,25 @@ Java_com_novoyuuparosk_iperf3gui_IperfRunner_runIperfLive(
/* Resolve callback method IDs up front so failures can be reported. */ /* Resolve callback method IDs up front so failures can be reported. */
jclass callback_cls = (*env)->GetObjectClass(env, callback); jclass callback_cls = (*env)->GetObjectClass(env, callback);
jmethodID mid_output = (*env)->GetMethodID( jmethodID mid_output = resolve_method(
env, callback_cls, "onOutput", "(Ljava/lang/String;)V"); env, callback_cls, "onOutput", "(Ljava/lang/String;)V");
jmethodID mid_error = (*env)->GetMethodID( jmethodID mid_error = resolve_method(
env, callback_cls, "onError", "(Ljava/lang/String;)V"); env, callback_cls, "onError", "(Ljava/lang/String;)V");
jmethodID mid_complete = (*env)->GetMethodID( jmethodID mid_complete = resolve_method(
env, callback_cls, "onComplete", "()V"); env, callback_cls, "onComplete", "()V");
/* If the names did not resolve there is no way to report anything: the
* reporting path is the thing that is missing. Bail out loudly instead.
*
* In practice this means R8 renamed the callback in a release build and
* android/app/proguard-rules.pro has stopped covering it. */
if (!mid_output || !mid_error || !mid_complete) {
LOGE("Callback methods did not resolve (onOutput=%p onError=%p "
"onComplete=%p) — check the -keep rules for IperfCallback",
mid_output, mid_error, mid_complete);
return;
}
/* Report a startup failure directly on the callback object and finish, /* Report a startup failure directly on the callback object and finish,
* so Dart's completer always resolves instead of waiting for a timeout. */ * so Dart's completer always resolves instead of waiting for a timeout. */
#define FAIL_EARLY(msg) do { \ #define FAIL_EARLY(msg) do { \
@@ -325,20 +320,20 @@ Java_com_novoyuuparosk_iperf3gui_IperfRunner_runIperfLive(
if (mid_complete) (*env)->CallVoidMethod(env, callback, mid_complete); \ if (mid_complete) (*env)->CallVoidMethod(env, callback, mid_complete); \
} while (0) } while (0)
/* Refuse to start a second concurrent test — the globals below hold /* Refuse to start a second concurrent test — the globals above hold
* exactly one test's worth of state. */ * exactly one test's worth of state. */
pthread_mutex_lock(&g_test_mutex); pthread_mutex_lock(&g_test_mutex);
int busy = (g_test != NULL); int busy = (g_test != NULL);
pthread_mutex_unlock(&g_test_mutex); pthread_mutex_unlock(&g_test_mutex);
if (busy) { if (busy) {
FAIL_EARLY("[iPerf JNI] A test is already running."); FAIL_EARLY("A test is already running.");
return; return;
} }
/* Create the iperf test object */ /* Create the iperf test object */
struct iperf_test *test = iperf_new_test(); struct iperf_test *test = iperf_new_test();
if (!test) { if (!test) {
FAIL_EARLY("[iPerf JNI] Failed to create iperf test"); FAIL_EARLY("Failed to create iperf test");
return; return;
} }
@@ -352,7 +347,7 @@ Java_com_novoyuuparosk_iperf3gui_IperfRunner_runIperfLive(
char **argv = build_argv(env, arguments, &total_argc); char **argv = build_argv(env, arguments, &total_argc);
if (!argv) { if (!argv) {
retire_test(); retire_test();
FAIL_EARLY("[iPerf JNI] Failed to allocate argv"); FAIL_EARLY("Failed to allocate argv");
return; return;
} }
@@ -365,19 +360,7 @@ Java_com_novoyuuparosk_iperf3gui_IperfRunner_runIperfLive(
if (iperf_parse_arguments(test, total_argc, argv) < 0) { if (iperf_parse_arguments(test, total_argc, argv) < 0) {
char errbuf[256]; char errbuf[256];
snprintf(errbuf, sizeof(errbuf), snprintf(errbuf, sizeof(errbuf),
"[iPerf JNI] Argument parse error: %s", iperf_strerror(i_errno)); "Argument parse error: %s", iperf_strerror(i_errno));
free_argv(argv, total_argc);
retire_test();
FAIL_EARLY(errbuf);
return;
}
/* Create a pipe to capture iperf's output */
int pipefd[2];
if (pipe(pipefd) != 0) {
char errbuf[256];
snprintf(errbuf, sizeof(errbuf),
"[iPerf JNI] Failed to create output pipe: %s", strerror(errno));
free_argv(argv, total_argc); free_argv(argv, total_argc);
retire_test(); retire_test();
FAIL_EARLY(errbuf); FAIL_EARLY(errbuf);
@@ -389,25 +372,11 @@ Java_com_novoyuuparosk_iperf3gui_IperfRunner_runIperfLive(
calloc(1, sizeof(struct iperf_run_state)); calloc(1, sizeof(struct iperf_run_state));
if (!state) { if (!state) {
free_argv(argv, total_argc); free_argv(argv, total_argc);
close(pipefd[0]);
close(pipefd[1]);
retire_test(); retire_test();
FAIL_EARLY("[iPerf JNI] Failed to allocate run state"); FAIL_EARLY("Failed to allocate run state");
return; return;
} }
FILE *outfile = fdopen(pipefd[1], "w");
if (!outfile) {
free(state);
free_argv(argv, total_argc);
close(pipefd[0]);
close(pipefd[1]);
retire_test();
FAIL_EARLY("[iPerf JNI] Failed to open output stream");
return;
}
/* Get JavaVM for reader-thread attachment */
JavaVM *jvm; JavaVM *jvm;
(*env)->GetJavaVM(env, &jvm); (*env)->GetJavaVM(env, &jvm);
@@ -415,14 +384,16 @@ Java_com_novoyuuparosk_iperf3gui_IperfRunner_runIperfLive(
state->mid_error = mid_error; state->mid_error = mid_error;
state->mid_complete = mid_complete; state->mid_complete = mid_complete;
state->callback_ref = (*env)->NewGlobalRef(env, callback); state->callback_ref = (*env)->NewGlobalRef(env, callback);
state->outfile = outfile;
state->pipe_fd[0] = pipefd[0];
state->pipe_fd[1] = pipefd[1];
state->jvm = jvm; state->jvm = jvm;
/* Redirect iperf's output to our pipe */ /* Deliver results as a stream of JSON events straight to
test->outfile = state->outfile; * json_event_callback, rather than as text through test->outfile.
setvbuf(test->outfile, NULL, _IOLBF, 0); /* Line-buffered */ * --json-stream sets both of these flags, so setting json_stream alone
* would leave iperf3 printing human-readable text as well. */
iperf_set_test_json_output(test, 1);
iperf_set_test_json_stream(test, 1);
iperf_set_test_json_callback(test, json_event_callback);
g_current_state = state;
/* Set temp directory for stream buffers (mkstemp in iperf_new_stream). /* Set temp directory for stream buffers (mkstemp in iperf_new_stream).
* On Android, /data/local/tmp is NOT writable from the app sandbox — * On Android, /data/local/tmp is NOT writable from the app sandbox —
@@ -430,22 +401,6 @@ Java_com_novoyuuparosk_iperf3gui_IperfRunner_runIperfLive(
* the strdup internally. */ * the strdup internally. */
iperf_set_test_template(test, g_tmp_template); iperf_set_test_template(test, g_tmp_template);
/* Spawn reader thread to forward iperf output to Java. Started before
* the test so early output is not lost, and before setjmp so the
* longjmp path can rely on reader_started being accurate. */
if (pthread_create(&state->reader_thread, NULL,
reader_thread_func, state) != 0) {
close_outfile(state);
close(pipefd[0]);
free_argv(argv, total_argc);
retire_test();
(*env)->DeleteGlobalRef(env, state->callback_ref);
free(state);
FAIL_EARLY("[iPerf JNI] Failed to start output reader thread");
return;
}
state->reader_started = 1;
#undef FAIL_EARLY #undef FAIL_EARLY
/* /*
@@ -462,8 +417,6 @@ Java_com_novoyuuparosk_iperf3gui_IperfRunner_runIperfLive(
signal(SIGPIPE, SIG_IGN); /* Ignore SIGPIPE for socket errors */ signal(SIGPIPE, SIG_IGN); /* Ignore SIGPIPE for socket errors */
iperf_catch_sigend(sigend_handler); iperf_catch_sigend(sigend_handler);
signal_output(env, state, "[iPerf JNI] Starting iPerf3 client...\n");
g_stop = 0; g_stop = 0;
int ret = iperf_run_client(test); int ret = iperf_run_client(test);
LOGI("iperf_run_client returned: %d i_errno=%d strerror=%s", LOGI("iperf_run_client returned: %d i_errno=%d strerror=%s",
@@ -478,8 +431,8 @@ Java_com_novoyuuparosk_iperf3gui_IperfRunner_runIperfLive(
} else { } else {
/* /*
* We got here via longjmp() from sigend_handler. * We got here via longjmp() from sigend_handler.
* iperf_cleanup_and_signal() closes the pipe, joins the reader and * iperf_cleanup_and_signal() frees everything, so there is nothing
* frees everything, so there is nothing to unwind by hand here. * to unwind by hand here.
*/ */
LOGI("Test interrupted by signal %d", g_signed_sig); LOGI("Test interrupted by signal %d", g_signed_sig);
g_stop = 1; g_stop = 1;
@@ -515,19 +468,7 @@ Java_com_novoyuuparosk_iperf3gui_IperfRunner_forceStopIperfTest(
pthread_mutex_unlock(&g_test_mutex); pthread_mutex_unlock(&g_test_mutex);
if (!requested) return; if (!requested) return;
LOGI("Graceful stop requested");
/* Notify Java */
jclass callback_cls = (*env)->GetObjectClass(env, callback);
jmethodID mid_output = (*env)->GetMethodID(
env, callback_cls, "onOutput", "(Ljava/lang/String;)V");
if (mid_output) {
jstring msg = (*env)->NewStringUTF(env,
"[iPerf JNI] Requested graceful stop.\n");
if (msg) {
(*env)->CallVoidMethod(env, callback, mid_output, msg);
(*env)->DeleteLocalRef(env, msg);
}
}
} }
/* ------------------------------------------------------------------ */ /* ------------------------------------------------------------------ */
+104 -19
View File
@@ -6,19 +6,25 @@ A Flutter-based Android GUI wrapper for iperf3, the popular network performance
``` ```
lib/ # Flutter/Dart application layer lib/ # Flutter/Dart application layer
├── main.dart # App entry point (MaterialApp) ├── main.dart # Composition root: picks the Iperf3Runner impl
├── domain/ # Business logic (platform-independent) ├── main_headless.dart # Runs a test with no widgets (see Layering)
├── domain/ # Pure Dart — no Flutter import
│ ├── models/ │ ├── models/
│ │ ├── test_configuration.dart # Server, port, duration, interval, parallel streams │ │ ├── test_configuration.dart # Server, port, duration, interval, parallel streams
│ │ └── iperf3_result.dart # Raw output + exit code │ │ ├── iperf3_result.dart # Raw output, exit code, stopped flag
├── data/ │ │ ├── iperf3_event.dart # Parsed --json-stream reports
│ │ └── iperf3_session.dart # One run accumulated: samples, totals, stats
│ └── services/ │ └── services/
│ └── iperf3_service.dart # Dart → MethodChannel bridge (async with Completer) │ └── iperf3_runner.dart # The contract the UI depends on
└── ui/ # Presentation layer ├── data/ # Transport — flutter/services only
│ └── services/
│ └── iperf3_service.dart # Iperf3Runner over MethodChannel → JNI
└── ui/ # Presentation
└── features/ └── features/
└── test_run/ └── test_run/
├── test_run_screen.dart # Server/port inputs + GO button ├── test_run_screen.dart # Inputs, GO/STOP, live transcript
└── test_run_view_model.dart # State machine: idle → running → completed/error ├── test_run_view_model.dart # idle → running → completed/error
└── iperf3_event_formatter.dart # Events → iperf3-style text
android/app/src/main/ android/app/src/main/
├── kotlin/ # Kotlin plugin layer ├── kotlin/ # Kotlin plugin layer
@@ -42,11 +48,55 @@ User taps GO
→ Kotlin IperfRunner: submits to the iperf3-run worker thread, returns at once → Kotlin IperfRunner: submits to the iperf3-run worker thread, returns at once
→ JNI C: build_argv() (prepends argv[0]) → iperf_parse_arguments() → JNI C: build_argv() (prepends argv[0]) → iperf_parse_arguments()
→ iperf_run_client(test) [blocks on the worker thread] → iperf_run_client(test) [blocks on the worker thread]
→ Reader thread pipes output → CallVoidMethod → main-thread hop → Dart onOutput → iperf3 json_callback → one JSON event per report → CallVoidMethod
→ Dart streams each line to the UI via Iperf3Service.outputLines → main-thread hop → Dart onOutput → Iperf3Event.parse()
→ Iperf3Service.events → view model: transcript + interval series + summary
→ On completion: Dart Completer resolves with Iperf3Result → On completion: Dart Completer resolves with Iperf3Result
``` ```
## Layering
Dependencies point inward: `ui → domain ← data`, never the reverse.
| Layer | May import | Holds |
|---|---|---|
| `domain` | nothing else in this package, no Flutter | models and the `Iperf3Runner` contract |
| `data` | `domain`, `package:flutter/services.dart` | the MethodChannel/JNI implementation |
| `ui` | `domain` | widgets, view model, formatting |
| `main.dart` | everything | the single place that picks an implementation |
The UI depends on `Iperf3Runner`, not on `Iperf3Service`, so presentation names
no transport. That is what lets `test/widget_test.dart` drive the real widget
tree against an in-memory runner with no MethodChannel, native library or
device — and what keeps a test double at five stable members instead of
mirroring the transport's whole surface.
**The core does not need the UI.** What happened during a run is accumulated by
`Iperf3Session` in the domain layer — samples, totals, errors, and the mean,
peak and retransmit figures over them. The view model holds no run data of its
own and the screen derives no numbers; both read the session. Replacing the
presentation layer therefore means rewriting rendering, not re-deriving results.
`lib/main_headless.dart` is the standing proof: it runs a full test through
`Iperf3Service` and `Iperf3Session` with `WidgetsFlutterBinding` but no
`runApp` — no widget tree, no render surface. If the run path ever starts
needing the UI, it stops working.
```bash
flutter run -t lib/main_headless.dart \
--dart-define=IPERF_SERVER=192.168.2.182 --dart-define=IPERF_STREAMS=4
```
Use it when a figure has to be trustworthy. A 4-stream local run reports
**30.2% local CPU headless against 79.9% through the UI** — the phone is near
CPU-bound at gigabit rates, so a repainting transcript measurably depresses
throughput. Numbers taken through the UI are pessimistic.
`test/architecture_test.dart` enforces all of this by reading the actual
imports under `lib/`, including a check that no fourth layer directory has
appeared unnoticed. Change the layering there when the layering should change;
don't work around it.
## Key Design Decisions ## Key Design Decisions
### JNI Over Process Execution ### JNI Over Process Execution
@@ -61,16 +111,51 @@ to the main looper — stalled every callback until the test was already over.
### Callback Mechanism ### Callback Mechanism
The JNI bridge uses `CallVoidMethod` on stored `jmethodID`s to invoke the Kotlin `IperfCallback` interface, NOT function pointer casts. Direct function pointer casts caused SIGBUS crashes on ARM due to JNINativeInterface method ID layout differences. The JNI bridge uses `CallVoidMethod` on stored `jmethodID`s to invoke the Kotlin `IperfCallback` interface, NOT function pointer casts. Direct function pointer casts caused SIGBUS crashes on ARM due to JNINativeInterface method ID layout differences.
### Output Streaming ### Output via json_callback, not a pipe
iperf3 output is redirected via pipe to a background reader thread that attaches The test runs with `json_output` and `json_stream` set and a `json_callback`
to the Java VM via `AttachCurrentThread` and invokes callbacks via installed, so iperf3 hands each report to the bridge as a JSON string and never
`CallVoidMethod`. Dart re-publishes each line on `Iperf3Service.outputLines`, so writes to `test->outfile`. `iperf.h` describes the hook as "allow user apps to
the transcript grows while the test runs. receive the JSON strings, instead of writing them to the output file" — this is
its intended use.
The reader blocks in `fgets()` and only unblocks on EOF, so the pipe's write end An earlier design piped `test->outfile` to a reader thread. That imposed two
must be closed **before** `pthread_join()` — joining first deadlocks the worker constraints, both of which were gotten wrong and deadlocked every test: the
thread. The JNI caller solely owns the run-state struct and frees it after the pipe's write end had to be closed *before* joining a reader blocked in
join; the reader must never free it. `fgets()`, and exactly one side could own the shared state struct. Reading from
the callback removes the pipe, the reader thread and both constraints. Don't
reintroduce it.
`json_callback` carries no user-data pointer, so the run state is reached
through a global published before `iperf_run_client()` and cleared afterwards;
only one test may run at a time, which `runIperfLive` enforces. The callback
fires on iperf3's reporting thread, so it resolves a `JNIEnv` for the calling
thread rather than reusing a stored one.
Dart parses each event into a sealed `Iperf3Event`; unrecognised output becomes
an `Iperf3LogLine` rather than being discarded. The UI rebuilds iperf3's text
layout from the events and keeps the interval series as data.
### Embedding a CLI in a long-lived process
iperf3's `main()` runs one test and exits, so anything it leaves behind is
reclaimed by the OS. Linked into an app process that runs tests repeatedly for
hours, every such leftover becomes this app's problem. What that costs in
practice:
- **Signal handlers are process-global.** `iperf_catch_sigend()` and
`signal(SIGPIPE, SIG_IGN)` change behaviour for the whole process, Flutter and
ART included. Handlers are restored to `SIG_DFL` when a test ends.
- **`g_sigend_jmp_buf` outlives its frame.** Harmless in a process about to
exit; a jump into a dead stack frame otherwise. Same fix as above.
- **Globals mean one test at a time.** `i_errno` and the bridge's own statics
hold a single test's worth of state, so concurrent runs are refused.
What iperf3 itself handles correctly, verified rather than assumed: per-stream
threads are joined (`iperf_client_api.c`), stream buffer fds are closed, and the
`mkstemp` temp file is `unlink`ed immediately after creation
(`iperf_api.c:4652`), so nothing accumulates in the cache dir. Measured across
four consecutive 4-stream runs on device, thread count returned to baseline
(33 → 40 mid-run → 34) and fd count returned exactly to baseline (175 → 183 →
175).
### Stop Handling ### Stop Handling
A stop shuts down the control socket, so `iperf_run_client()` returns -1 with A stop shuts down the control socket, so `iperf_run_client()` returns -1 with
+57 -40
View File
@@ -1,25 +1,33 @@
import 'dart:async'; import 'dart:async';
import 'dart:developer' as developer;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:iperf3gui/domain/models/iperf3_event.dart';
import 'package:iperf3gui/domain/models/iperf3_result.dart'; import 'package:iperf3gui/domain/models/iperf3_result.dart';
import 'package:iperf3gui/domain/models/test_configuration.dart'; import 'package:iperf3gui/domain/models/test_configuration.dart';
import 'package:iperf3gui/domain/services/iperf3_runner.dart';
/// Service that runs iperf3 via JNI (native library). /// [Iperf3Runner] backed by the native iperf3 library over a MethodChannel.
/// ///
/// On Android, iperf3 is compiled into the app as a shared library (.so). /// On Android, iperf3 is compiled into the app as a shared library (.so).
/// This avoids SELinux restrictions on executing ELF binaries from assets. /// This avoids SELinux restrictions on executing ELF binaries from assets.
/// ///
/// The service talks to the native layer over a MethodChannel. Native output /// The service talks to the native layer over a MethodChannel. The test runs
/// arrives line by line on [outputLines] while the test runs; [run] resolves /// in `--json-stream` mode, so each native report arrives as one JSON object;
/// with the accumulated transcript once the native layer reports completion. /// they are parsed and published on [events] while the test runs. [run]
class Iperf3Service { /// resolves once the native layer reports completion, carrying the raw JSON
/// lines as the result's output.
class Iperf3Service implements Iperf3Runner {
Iperf3Service() { Iperf3Service() {
_channel.setMethodCallHandler(_handleNativeCall); _channel.setMethodCallHandler(_handleNativeCall);
} }
static const MethodChannel _channel = /// A channel's handler is keyed by channel name in the binary messenger, so
MethodChannel('com.novoyuuparosk.iperf3gui/iperf'); /// it is process-global: constructing a second instance would take the
/// handler away from the first. The app composes exactly one, in main().
final MethodChannel _channel = const MethodChannel(_channelName);
static const String _channelName = 'com.novoyuuparosk.iperf3gui/iperf';
/// Exit code reported when the native layer signalled an error. /// Exit code reported when the native layer signalled an error.
static const int exitCodeNativeError = 1; static const int exitCodeNativeError = 1;
@@ -33,22 +41,23 @@ class Iperf3Service {
/// Exit code reported when the native layer never signalled completion. /// Exit code reported when the native layer never signalled completion.
static const int exitCodeTimeout = -3; static const int exitCodeTimeout = -3;
/// Lines emitted by the native layer during the current run. /// Events parsed from the native layer during the current run.
final StreamController<String> _outputController = final StreamController<Iperf3Event> _eventController =
StreamController<String>.broadcast(); StreamController<Iperf3Event>.broadcast();
/// Live output, one line per event. Use this to render progress; [run]'s /// Live reports, one event per native report. Use this to render progress.
/// result carries the same text joined together. @override
Stream<String> get outputLines => _outputController.stream; Stream<Iperf3Event> get events => _eventController.stream;
/// Transcript of the current (or most recent) run. /// Raw JSON lines received during the current (or most recent) run.
final List<String> _outputBuffer = []; final List<String> _rawLines = [];
/// Completer that resolves when the native iperf3 test finishes. /// Completer that resolves when the native iperf3 test finishes.
Completer<Iperf3Result>? _runCompleter; Completer<Iperf3Result>? _runCompleter;
/// Whether iperf3 is currently running. /// Whether iperf3 is currently running.
bool _isRunning = false; bool _isRunning = false;
@override
bool get isRunning => _isRunning; bool get isRunning => _isRunning;
/// Whether the native layer reported an error during this run. /// Whether the native layer reported an error during this run.
@@ -58,25 +67,28 @@ class Iperf3Service {
bool _stopRequested = false; bool _stopRequested = false;
/// Cancel any running test. /// Cancel any running test.
@override
Future<void> stop() async { Future<void> stop() async {
if (!_isRunning) return; if (!_isRunning) return;
_stopRequested = true; _stopRequested = true;
try { try {
await _channel.invokeMethod('stopIperf'); await _channel.invokeMethod('stopIperf');
} catch (e) { } catch (e) {
debugPrint('Iperf3Service: error stopping: $e'); _log('Iperf3Service: error stopping: $e');
} }
} }
/// Release the stream controller. Call from the owner's dispose(). /// Release the stream controller. Call from the owner's dispose().
@override
Future<void> dispose() async { Future<void> dispose() async {
_channel.setMethodCallHandler(null); _channel.setMethodCallHandler(null);
await _outputController.close(); await _eventController.close();
} }
/// Run iperf3 with the given configuration. /// Run iperf3 with the given configuration.
/// ///
/// Returns an [Iperf3Result] with the full output and an exit code. /// Returns an [Iperf3Result] with the full output and an exit code.
@override
Future<Iperf3Result> run(TestConfiguration config) async { Future<Iperf3Result> run(TestConfiguration config) async {
if (_isRunning) { if (_isRunning) {
return const Iperf3Result( return const Iperf3Result(
@@ -88,10 +100,10 @@ class Iperf3Service {
_isRunning = true; _isRunning = true;
_sawError = false; _sawError = false;
_stopRequested = false; _stopRequested = false;
_outputBuffer.clear(); _rawLines.clear();
final args = config.toCliArgs(); final args = config.toCliArgs();
debugPrint('Iperf3Service: running: ${args.join(" ")}'); _log('Iperf3Service: running: ${args.join(" ")}');
final completer = Completer<Iperf3Result>(); final completer = Completer<Iperf3Result>();
_runCompleter = completer; _runCompleter = completer;
@@ -99,8 +111,8 @@ class Iperf3Service {
try { try {
await _channel.invokeMethod('runIperf', {'args': args}); await _channel.invokeMethod('runIperf', {'args': args});
} catch (e, stackTrace) { } catch (e, stackTrace) {
debugPrint('Iperf3Service exception: $e'); _log('Iperf3Service exception: $e');
debugPrint('Iperf3Service stack: $stackTrace'); _log('Iperf3Service stack: $stackTrace');
_finishRun(); _finishRun();
return Iperf3Result( return Iperf3Result(
rawOutput: 'Error starting iperf3: $e', rawOutput: 'Error starting iperf3: $e',
@@ -114,22 +126,22 @@ class Iperf3Service {
return await completer.future.timeout( return await completer.future.timeout(
config.duration + const Duration(seconds: 45), config.duration + const Duration(seconds: 45),
onTimeout: () { onTimeout: () {
debugPrint('Iperf3Service: timeout, stopping test'); _log('Iperf3Service: timeout, stopping test');
// Ask the native layer to wind down, then release local state so a // Ask the native layer to wind down, then release local state so a
// stuck run can never lock the UI out of starting another test. // stuck run can never lock the UI out of starting another test.
_channel.invokeMethod('stopIperf').catchError((Object e) { _channel.invokeMethod('stopIperf').catchError((Object e) {
debugPrint('Iperf3Service: error stopping after timeout: $e'); _log('Iperf3Service: error stopping after timeout: $e');
return null; return null;
}); });
_emit('[ERROR] Timed out waiting for iperf3 to finish.'); _publish(const Iperf3Error('Timed out waiting for iperf3 to finish.'));
return Iperf3Result( return Iperf3Result(
rawOutput: _transcript(), rawOutput: _rawOutput(),
exitCode: exitCodeTimeout, exitCode: exitCodeTimeout,
); );
}, },
); );
} catch (e) { } catch (e) {
debugPrint('Iperf3Service: error waiting for completion: $e'); _log('Iperf3Service: error waiting for completion: $e');
return Iperf3Result( return Iperf3Result(
rawOutput: 'Test failed: $e', rawOutput: 'Test failed: $e',
exitCode: exitCodeStartFailed, exitCode: exitCodeStartFailed,
@@ -145,7 +157,12 @@ class Iperf3Service {
case 'onOutput': case 'onOutput':
final output = call.arguments['output'] as String?; final output = call.arguments['output'] as String?;
if (output != null) { if (output != null) {
_emit(output); _rawLines.add(output);
final event = Iperf3Event.parse(output);
// iperf3 reports a failed test as an `error` event rather than a
// non-zero return, so this is where most failures surface.
if (event is Iperf3Error) _sawError = true;
_publish(event);
} }
case 'onError': case 'onError':
final error = call.arguments['error'] as String?; final error = call.arguments['error'] as String?;
@@ -153,15 +170,15 @@ class Iperf3Service {
// Not terminal on its own — iperf3 reports the failure reason and // Not terminal on its own — iperf3 reports the failure reason and
// then completes, so wait for onComplete before resolving. // then completes, so wait for onComplete before resolving.
_sawError = true; _sawError = true;
_emit('[ERROR] $error'); _publish(Iperf3Error(error));
} }
case 'onComplete': case 'onComplete':
debugPrint('Iperf3Service: test completed'); _log('Iperf3Service: test completed');
final completer = _runCompleter; final completer = _runCompleter;
if (completer != null && !completer.isCompleted) { if (completer != null && !completer.isCompleted) {
completer.complete( completer.complete(
Iperf3Result( Iperf3Result(
rawOutput: _transcript(), rawOutput: _rawOutput(),
// A user-requested stop is a normal outcome, not a failure. // A user-requested stop is a normal outcome, not a failure.
exitCode: exitCode:
(_sawError && !_stopRequested) ? exitCodeNativeError : 0, (_sawError && !_stopRequested) ? exitCodeNativeError : 0,
@@ -170,21 +187,18 @@ class Iperf3Service {
); );
} }
default: default:
debugPrint('Iperf3Service: unhandled native call ${call.method}'); _log('Iperf3Service: unhandled native call ${call.method}');
} }
} }
void _emit(String line) { void _publish(Iperf3Event event) {
_outputBuffer.add(line); if (!_eventController.isClosed) {
if (!_outputController.isClosed) { _eventController.add(event);
_outputController.add(line);
} }
debugPrint('Iperf3Service output: ${line.trimRight()}');
} }
/// Native output already carries its own newlines; keep it verbatim except /// The raw JSON stream as received, one event per line.
/// for lines we synthesised ourselves. String _rawOutput() => _rawLines
String _transcript() => _outputBuffer
.map((line) => line.endsWith('\n') ? line : '$line\n') .map((line) => line.endsWith('\n') ? line : '$line\n')
.join(); .join();
@@ -193,3 +207,6 @@ class Iperf3Service {
_runCompleter = null; _runCompleter = null;
} }
} }
void _log(String message) =>
developer.log(message, name: 'Iperf3Service');
+238
View File
@@ -0,0 +1,238 @@
import 'dart:convert';
/// One report from iperf3's `--json-stream` output.
///
/// iperf3 emits `{"event": "<name>", "data": {...}}` per report; the events a
/// client run produces are `start`, `interval`, `end` and `error`. The bridge
/// adds `jni_stopped` when a run ended because the user stopped it.
sealed class Iperf3Event {
const Iperf3Event();
/// Parse one line of `--json-stream` output.
///
/// Returns an [Iperf3LogLine] for anything that is not a recognised JSON
/// event, so unexpected output is surfaced rather than dropped.
static Iperf3Event parse(String line) {
final trimmed = line.trim();
if (trimmed.isEmpty) return const Iperf3LogLine('');
if (!trimmed.startsWith('{')) return Iperf3LogLine(trimmed);
final Object? decoded;
try {
decoded = jsonDecode(trimmed);
} on FormatException {
return Iperf3LogLine(trimmed);
}
if (decoded is! Map<String, dynamic>) return Iperf3LogLine(trimmed);
final event = decoded['event'];
final data = decoded['data'];
if (event is! String) return Iperf3LogLine(trimmed);
final map = data is Map<String, dynamic> ? data : const <String, dynamic>{};
return switch (event) {
'start' => Iperf3Start.fromJson(map),
'interval' => Iperf3Interval.fromJson(map),
'end' => Iperf3End.fromJson(map),
'error' => Iperf3Error(_stringOf(data) ?? 'unknown error'),
'jni_stopped' => const Iperf3Stopped(),
_ => Iperf3LogLine(trimmed),
};
}
static String? _stringOf(Object? value) {
if (value is String) return value;
if (value is Map<String, dynamic>) {
final error = value['error'];
if (error is String) return error;
}
return null;
}
}
/// Connection details, emitted once at the start of a test.
class Iperf3Start extends Iperf3Event {
final String? targetHost;
final int? targetPort;
final int? streamCount;
final int? durationSeconds;
final String? protocol;
const Iperf3Start({
this.targetHost,
this.targetPort,
this.streamCount,
this.durationSeconds,
this.protocol,
});
factory Iperf3Start.fromJson(Map<String, dynamic> data) {
final connecting = data['connecting_to'];
final testStart = data['test_start'];
return Iperf3Start(
targetHost: connecting is Map ? connecting['host'] as String? : null,
targetPort: connecting is Map ? _asInt(connecting['port']) : null,
streamCount: testStart is Map ? _asInt(testStart['num_streams']) : null,
durationSeconds: testStart is Map ? _asInt(testStart['duration']) : null,
protocol: testStart is Map ? testStart['protocol'] as String? : null,
);
}
}
/// One reporting interval, summed across all streams.
class Iperf3Interval extends Iperf3Event {
final double start;
final double end;
final int bytes;
final double bitsPerSecond;
final int? retransmits;
final bool omitted;
/// Per-stream figures, when more than one stream is running.
final List<Iperf3StreamInterval> streams;
const Iperf3Interval({
required this.start,
required this.end,
required this.bytes,
required this.bitsPerSecond,
this.retransmits,
this.omitted = false,
this.streams = const [],
});
factory Iperf3Interval.fromJson(Map<String, dynamic> data) {
// Non-bidirectional runs use "sum"; bidir adds "sum_bidir_reverse".
final sum = data['sum'] ?? data['sum_bidir_reverse'];
final sumMap = sum is Map<String, dynamic> ? sum : const <String, dynamic>{};
final rawStreams = data['streams'];
return Iperf3Interval(
start: _asDouble(sumMap['start']) ?? 0,
end: _asDouble(sumMap['end']) ?? 0,
bytes: _asInt(sumMap['bytes']) ?? 0,
bitsPerSecond: _asDouble(sumMap['bits_per_second']) ?? 0,
retransmits: _asInt(sumMap['retransmits']),
omitted: sumMap['omitted'] == true,
streams: rawStreams is List
? rawStreams
.whereType<Map<String, dynamic>>()
.map(Iperf3StreamInterval.fromJson)
.toList(growable: false)
: const [],
);
}
}
/// One stream's contribution to an interval.
class Iperf3StreamInterval {
final int? socket;
final int bytes;
final double bitsPerSecond;
final int? retransmits;
final int? sendCwnd;
final int? rtt;
const Iperf3StreamInterval({
this.socket,
required this.bytes,
required this.bitsPerSecond,
this.retransmits,
this.sendCwnd,
this.rtt,
});
factory Iperf3StreamInterval.fromJson(Map<String, dynamic> data) {
return Iperf3StreamInterval(
socket: _asInt(data['socket']),
bytes: _asInt(data['bytes']) ?? 0,
bitsPerSecond: _asDouble(data['bits_per_second']) ?? 0,
retransmits: _asInt(data['retransmits']),
sendCwnd: _asInt(data['snd_cwnd']),
rtt: _asInt(data['rtt']),
);
}
}
/// Totals for the whole test, emitted once at the end.
class Iperf3End extends Iperf3Event {
final Iperf3Total? sent;
final Iperf3Total? received;
final double? hostCpuPercent;
final double? remoteCpuPercent;
const Iperf3End({
this.sent,
this.received,
this.hostCpuPercent,
this.remoteCpuPercent,
});
factory Iperf3End.fromJson(Map<String, dynamic> data) {
final cpu = data['cpu_utilization_percent'];
return Iperf3End(
sent: Iperf3Total.fromJson(
data['sum_sent'] ?? data['sum_sent_bidir_reverse']),
received: Iperf3Total.fromJson(
data['sum_received'] ?? data['sum_received_bidir_reverse']),
hostCpuPercent: cpu is Map ? _asDouble(cpu['host_total']) : null,
remoteCpuPercent: cpu is Map ? _asDouble(cpu['remote_total']) : null,
);
}
}
/// A sent or received total from the `end` event.
class Iperf3Total {
final double seconds;
final int bytes;
final double bitsPerSecond;
final int? retransmits;
const Iperf3Total({
required this.seconds,
required this.bytes,
required this.bitsPerSecond,
this.retransmits,
});
static Iperf3Total? fromJson(Object? data) {
if (data is! Map<String, dynamic>) return null;
return Iperf3Total(
seconds: _asDouble(data['seconds']) ?? 0,
bytes: _asInt(data['bytes']) ?? 0,
bitsPerSecond: _asDouble(data['bits_per_second']) ?? 0,
retransmits: _asInt(data['retransmits']),
);
}
}
/// iperf3 reported an error for this test.
class Iperf3Error extends Iperf3Event {
final String message;
const Iperf3Error(this.message);
}
/// The run ended because the user stopped it.
class Iperf3Stopped extends Iperf3Event {
const Iperf3Stopped();
}
/// Output that was not a recognised JSON event.
class Iperf3LogLine extends Iperf3Event {
final String text;
const Iperf3LogLine(this.text);
}
int? _asInt(Object? value) => switch (value) {
int v => v,
double v => v.round(),
String v => int.tryParse(v),
_ => null,
};
double? _asDouble(Object? value) => switch (value) {
double v => v,
int v => v.toDouble(),
String v => double.tryParse(v),
_ => null,
};
+114
View File
@@ -0,0 +1,114 @@
import 'package:iperf3gui/domain/models/iperf3_event.dart';
/// The accumulated state of one iperf3 run.
///
/// Fed the event stream one report at a time, this is the answer to "what
/// happened during this test" — the interval series, the end totals, any
/// errors, and the statistics derived from them.
///
/// It lives in the domain layer on purpose: it is what has to be *correct*,
/// independent of how anything chooses to draw it. A different UI, a headless
/// run or a future export path all consume the same object, and none of them
/// re-derive a mean or re-decide whether a warm-up interval counts.
class Iperf3Session {
Iperf3Start? _start;
/// Connection details, once the run has reported them.
Iperf3Start? get start => _start;
final List<Iperf3Interval> _intervals = [];
/// Throughput samples in arrival order, warm-up intervals excluded.
List<Iperf3Interval> get intervals => List.unmodifiable(_intervals);
Iperf3End? _summary;
/// Sent/received totals, once the run has finished.
Iperf3End? get summary => _summary;
final List<String> _errors = [];
/// Errors reported during the run, in order.
List<String> get errors => List.unmodifiable(_errors);
bool _stopped = false;
/// Whether the run ended because it was asked to stop.
bool get stopped => _stopped;
/// Whether iperf3 reported any error.
bool get hasError => _errors.isNotEmpty;
/// Whether anything at all has been recorded.
bool get isEmpty =>
_start == null && _intervals.isEmpty && _summary == null && !hasError;
/// How many throughput samples have been recorded.
int get sampleCount => _intervals.length;
/// Throughput of the most recent sample, or null before the first one.
double? get latestBitsPerSecond =>
_intervals.isEmpty ? null : _intervals.last.bitsPerSecond;
/// Mean throughput across the samples, or null before the first one.
///
/// This is the mean of the per-interval rates, which is not identical to the
/// run's overall rate when intervals differ in length — prefer
/// [summary]'s totals for the headline figure once it is available.
double? get meanBitsPerSecond {
if (_intervals.isEmpty) return null;
final total = _intervals.fold<double>(0, (sum, i) => sum + i.bitsPerSecond);
return total / _intervals.length;
}
/// Highest sampled throughput, or null before the first sample.
double? get peakBitsPerSecond {
if (_intervals.isEmpty) return null;
return _intervals
.map((i) => i.bitsPerSecond)
.reduce((a, b) => a > b ? a : b);
}
/// Total bytes across the recorded samples.
int get sampledBytes => _intervals.fold<int>(0, (sum, i) => sum + i.bytes);
/// Total retransmits across the samples, or null if none were reported.
///
/// UDP tests report no retransmit counts, so null means "not measured"
/// rather than zero.
int? get totalRetransmits {
final reported =
_intervals.map((i) => i.retransmits).whereType<int>().toList();
if (reported.isEmpty) return null;
return reported.fold<int>(0, (sum, r) => sum + r);
}
/// Record one report.
void add(Iperf3Event event) {
switch (event) {
case Iperf3Start e:
_start = e;
case Iperf3Interval e:
// Warm-up intervals (-O) are marked omitted by iperf3 and must not
// drag the statistics down.
if (!e.omitted) _intervals.add(e);
case Iperf3End e:
_summary = e;
case Iperf3Error e:
_errors.add(e.message);
case Iperf3Stopped _:
_stopped = true;
case Iperf3LogLine _:
break;
}
}
/// Forget everything, ready for another run.
void clear() {
_start = null;
_intervals.clear();
_summary = null;
_errors.clear();
_stopped = false;
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ class TestConfiguration {
final int parallelStreams; final int parallelStreams;
const TestConfiguration({ const TestConfiguration({
this.server = 'iperf.es.net', this.server = 'speedtest.uztelecom.uz',
this.port = 5201, this.port = 5201,
this.duration = const Duration(seconds: 10), this.duration = const Duration(seconds: 10),
this.interval = 1, this.interval = 1,
+36
View File
@@ -0,0 +1,36 @@
import 'package:iperf3gui/domain/models/iperf3_event.dart';
import 'package:iperf3gui/domain/models/iperf3_result.dart';
import 'package:iperf3gui/domain/models/test_configuration.dart';
/// Runs iperf3 tests and reports what happens.
///
/// This is the whole contract the UI depends on. It is deliberately pure Dart —
/// no Flutter import — so the presentation layer never names a transport. The
/// Android build supplies a MethodChannel-and-JNI implementation
/// (`Iperf3Service`); a test, a desktop build or a headless tool can supply
/// its own without touching anything above this line.
abstract interface class Iperf3Runner {
/// Reports parsed from the running test, one event per iperf3 report.
///
/// A broadcast stream: it may have no listener, and late listeners miss
/// earlier events rather than replaying them.
Stream<Iperf3Event> get events;
/// Whether a test is in flight right now.
bool get isRunning;
/// Run a test to completion and resolve with its outcome.
///
/// Resolves rather than throws for an iperf3-level failure — the failure is
/// carried in [Iperf3Result.exitCode]. Implementations must always resolve,
/// including on internal error, so a caller can never be left awaiting.
Future<Iperf3Result> run(TestConfiguration config);
/// Ask a running test to stop early. A no-op when nothing is running.
///
/// The run's future still resolves, with [Iperf3Result.stopped] set.
Future<void> stop();
/// Release resources. The instance is unusable afterwards.
Future<void> dispose();
}
+11 -6
View File
@@ -1,17 +1,22 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:iperf3gui/data/services/iperf3_service.dart';
import 'package:iperf3gui/domain/services/iperf3_runner.dart';
import 'package:iperf3gui/ui/features/test_run/test_run_screen.dart'; import 'package:iperf3gui/ui/features/test_run/test_run_screen.dart';
/// Application entry point. /// Application entry point, and the composition root.
/// ///
/// iperf3 is now compiled as a native shared library (libiperf3jni.so) /// This is the only place that names a concrete [Iperf3Runner]. Everything
/// and accessed via JNI — no binary extraction or chmod needed. /// above the data layer depends on the interface, so swapping the transport —
/// or running the UI against a fake — touches nothing but this file.
Future<void> main() async { Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
runApp(const Iperf3GuiApp()); runApp(Iperf3GuiApp(runner: Iperf3Service()));
} }
class Iperf3GuiApp extends StatelessWidget { class Iperf3GuiApp extends StatelessWidget {
const Iperf3GuiApp({super.key}); const Iperf3GuiApp({required this.runner, super.key});
final Iperf3Runner runner;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -21,7 +26,7 @@ class Iperf3GuiApp extends StatelessWidget {
colorSchemeSeed: Colors.blue, colorSchemeSeed: Colors.blue,
useMaterial3: true, useMaterial3: true,
), ),
home: const TestRunScreen(), home: TestRunScreen(runner: runner),
); );
} }
} }
+105
View File
@@ -0,0 +1,105 @@
// Headless entry point: runs one iperf3 test with no widgets.
//
// This exists to keep the core honest. If anything in the run path ever starts
// depending on the UI, this stops compiling or stops working — a claim about
// separation that is checked rather than asserted.
//
// It is also the low-noise way to measure. The UI competes with the test for
// CPU (a gigabit run can put the phone near CPU-bound), so figures taken here
// are cleaner than figures taken with a transcript repainting alongside.
//
// flutter run -t lib/main_headless.dart \
// --dart-define=IPERF_SERVER=192.168.2.182 \
// --dart-define=IPERF_STREAMS=4
//
// Nothing below imports lib/ui, and test/architecture_test.dart enforces that.
import 'package:flutter/widgets.dart' show WidgetsFlutterBinding;
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:iperf3gui/data/services/iperf3_service.dart';
import 'package:iperf3gui/domain/models/iperf3_event.dart';
import 'package:iperf3gui/domain/models/iperf3_session.dart';
import 'package:iperf3gui/domain/models/test_configuration.dart';
import 'package:iperf3gui/domain/services/iperf3_runner.dart';
/// Test parameters, supplied at build time with --dart-define.
const String _server = String.fromEnvironment('IPERF_SERVER',
defaultValue: 'speedtest.uztelecom.uz');
const int _port = int.fromEnvironment('IPERF_PORT', defaultValue: 5201);
const int _seconds = int.fromEnvironment('IPERF_SECONDS', defaultValue: 10);
const int _streams = int.fromEnvironment('IPERF_STREAMS', defaultValue: 1);
Future<void> main() async {
// Required for the MethodChannel. Notably NOT runApp() — there is no widget
// tree, no render surface and no Flutter UI thread work in this process.
WidgetsFlutterBinding.ensureInitialized();
const config = TestConfiguration(
server: _server,
port: _port,
duration: Duration(seconds: _seconds),
parallelStreams: _streams,
);
final Iperf3Runner runner = Iperf3Service();
final session = Iperf3Session();
final subscription = runner.events.listen((event) {
session.add(event);
if (event is Iperf3Interval && !event.omitted) {
_out('interval ${event.start.toStringAsFixed(2)}-'
'${event.end.toStringAsFixed(2)}s '
'${_mbits(event.bitsPerSecond)} Mbit/s'
'${event.retransmits != null ? ' retr=${event.retransmits}' : ''}');
} else if (event is Iperf3Error) {
_out('error: ${event.message}');
}
});
_out('running iperf3 -c ${config.server} -p ${config.port} '
'-t ${config.duration.inSeconds} -P ${config.parallelStreams}');
final result = await runner.run(config);
await subscription.cancel();
await runner.dispose();
_report(result.exitCode, session);
}
void _report(int exitCode, Iperf3Session session) {
_out('--- result ---');
_out('exit code: $exitCode');
_out('samples: ${session.sampleCount}');
final mean = session.meanBitsPerSecond;
final peak = session.peakBitsPerSecond;
if (mean != null) _out('mean: ${_mbits(mean)} Mbit/s');
if (peak != null) _out('peak: ${_mbits(peak)} Mbit/s');
final retr = session.totalRetransmits;
_out('retransmits: ${retr ?? 'not measured'}');
final sent = session.summary?.sent;
final received = session.summary?.received;
if (sent != null) {
_out('sent: ${_mbits(sent.bitsPerSecond)} Mbit/s '
'over ${sent.seconds.toStringAsFixed(2)}s');
}
if (received != null) {
_out('received: ${_mbits(received.bitsPerSecond)} Mbit/s '
'over ${received.seconds.toStringAsFixed(2)}s');
}
final cpu = session.summary?.hostCpuPercent;
if (cpu != null) _out('local cpu: ${cpu.toStringAsFixed(1)}%');
if (session.stopped) _out('ended early: stopped');
for (final error in session.errors) {
_out('error: $error');
}
}
String _mbits(double bitsPerSecond) =>
(bitsPerSecond / 1e6).toStringAsFixed(1);
void _out(String line) => debugPrint('[iperf3-headless] $line');
@@ -0,0 +1,95 @@
import 'package:iperf3gui/domain/models/iperf3_event.dart';
/// Renders parsed iperf3 events as the kind of line iperf3 itself would print.
///
/// The app consumes `--json-stream`, so the familiar text layout has to be
/// rebuilt here. Keeping it in one pure function makes it testable and leaves
/// the structured events untouched for anything else that wants them.
String? formatIperf3Event(Iperf3Event event) {
return switch (event) {
Iperf3Start e => _formatStart(e),
Iperf3Interval e => _formatInterval(e),
Iperf3End e => _formatEnd(e),
Iperf3Error e => 'iperf3 error: ${e.message}',
Iperf3Stopped _ => 'Stopped by user.',
Iperf3LogLine e => e.text.isEmpty ? null : e.text,
};
}
String _formatStart(Iperf3Start e) {
final parts = <String>[];
if (e.targetHost != null) {
final port = e.targetPort != null ? ', port ${e.targetPort}' : '';
parts.add('Connecting to host ${e.targetHost}$port');
}
final detail = <String>[
if (e.protocol != null) e.protocol!,
if (e.streamCount != null)
'${e.streamCount} stream${e.streamCount == 1 ? '' : 's'}',
if (e.durationSeconds != null) '${e.durationSeconds}s',
];
if (detail.isNotEmpty) parts.add(detail.join(' · '));
return parts.isEmpty ? '' : parts.join('\n');
}
String _formatInterval(Iperf3Interval e) {
final window = '${_seconds(e.start)}-${_seconds(e.end)} sec';
final line = StringBuffer('[SUM] $window '
'${formatBytes(e.bytes)} ${formatBitrate(e.bitsPerSecond)}');
if (e.retransmits != null) {
line.write(' ${e.retransmits} retr');
}
if (e.omitted) line.write(' (omitted)');
return line.toString();
}
String _formatEnd(Iperf3End e) {
final lines = <String>['- ' * 20];
final sent = e.sent;
final received = e.received;
if (sent != null) {
lines.add('[SUM] 0.00-${_seconds(sent.seconds)} sec '
'${formatBytes(sent.bytes)} ${formatBitrate(sent.bitsPerSecond)}'
'${sent.retransmits != null ? ' ${sent.retransmits} retr' : ''}'
' sender');
}
if (received != null) {
lines.add('[SUM] 0.00-${_seconds(received.seconds)} sec '
'${formatBytes(received.bytes)} '
'${formatBitrate(received.bitsPerSecond)} receiver');
}
if (e.hostCpuPercent != null) {
lines.add('CPU: local ${e.hostCpuPercent!.toStringAsFixed(1)}%'
'${e.remoteCpuPercent != null ? ', remote ${e.remoteCpuPercent!.toStringAsFixed(1)}%' : ''}');
}
return lines.join('\n');
}
String _seconds(double value) => value.toStringAsFixed(2);
/// Byte totals the way iperf3 prints them — `93.8 MBytes`.
String formatBytes(int bytes) {
const units = ['Bytes', 'KBytes', 'MBytes', 'GBytes', 'TBytes'];
var value = bytes.toDouble();
var unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit++;
}
final precision = value >= 100 ? 0 : (value >= 10 ? 1 : 2);
return '${value.toStringAsFixed(precision)} ${units[unit]}';
}
/// Bitrates the way iperf3 prints them — `786 Mbits/sec`. Decimal units, since
/// network rates are powers of ten while transfer totals are powers of two.
String formatBitrate(double bitsPerSecond) {
const units = ['bits/sec', 'Kbits/sec', 'Mbits/sec', 'Gbits/sec'];
var value = bitsPerSecond;
var unit = 0;
while (value >= 1000 && unit < units.length - 1) {
value /= 1000;
unit++;
}
final precision = value >= 100 ? 0 : (value >= 10 ? 1 : 2);
return '${value.toStringAsFixed(precision)} ${units[unit]}';
}
+70 -8
View File
@@ -1,23 +1,25 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:provider/provider.dart'; import 'package:provider/provider.dart';
import 'package:iperf3gui/data/services/iperf3_service.dart';
import 'package:iperf3gui/domain/models/test_configuration.dart'; import 'package:iperf3gui/domain/models/test_configuration.dart';
import 'package:iperf3gui/domain/services/iperf3_runner.dart';
import 'package:iperf3gui/ui/features/test_run/iperf3_event_formatter.dart';
import 'package:iperf3gui/ui/features/test_run/test_run_view_model.dart'; import 'package:iperf3gui/ui/features/test_run/test_run_view_model.dart';
/// Main test run screen. /// Main test run screen.
/// ///
/// iperf3 is compiled as a native shared library (libiperf3jni.so) and accessed /// Takes an [Iperf3Runner] rather than constructing one, so this layer names no
/// via JNI, so there is no binary extraction or chmod step. /// transport: the Android app injects the JNI-backed implementation from
/// main(), and a test injects a fake.
class TestRunScreen extends StatelessWidget { class TestRunScreen extends StatelessWidget {
const TestRunScreen({super.key}); const TestRunScreen({required this.runner, super.key});
final Iperf3Runner runner;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return ChangeNotifierProvider( return ChangeNotifierProvider(
create: (_) => TestRunViewModel( create: (_) => TestRunViewModel(iperf3Service: runner),
iperf3Service: Iperf3Service(),
),
child: const _TestRunContent(), child: const _TestRunContent(),
); );
} }
@@ -108,7 +110,7 @@ class _TestRunContentState extends State<_TestRunContent> {
autocorrect: false, autocorrect: false,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Server', labelText: 'Server',
hintText: 'e.g. iperf.es.net or 192.168.1.1', hintText: 'e.g. speedtest.uztelecom.uz or 192.168.1.1',
), ),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
@@ -193,6 +195,37 @@ class _TestRunContentState extends State<_TestRunContent> {
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
// Live throughput figures. Every number here is read off the
// session; none are computed in the widget tree.
Consumer<TestRunViewModel>(
builder: (context, vm, _) {
final session = vm.session;
final latest = session.latestBitsPerSecond;
final mean = session.meanBitsPerSecond;
final peak = session.peakBitsPerSecond;
if (latest == null || mean == null || peak == null) {
return const SizedBox.shrink();
}
final total = session.summary?.sent;
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_Stat(
label: total != null ? 'total' : 'now',
value: formatBitrate(total?.bitsPerSecond ?? latest),
),
_Stat(label: 'avg', value: formatBitrate(mean)),
_Stat(label: 'peak', value: formatBitrate(peak)),
_Stat(
label: 'samples', value: '${session.sampleCount}'),
],
),
);
},
),
// Live output // Live output
Expanded( Expanded(
child: Container( child: Container(
@@ -229,3 +262,32 @@ class _TestRunContentState extends State<_TestRunContent> {
); );
} }
} }
/// One figure in the throughput row.
class _Stat extends StatelessWidget {
const _Stat({required this.label, required this.value});
final String label;
final String value;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: theme.textTheme.labelSmall
?.copyWith(color: theme.colorScheme.onSurfaceVariant),
),
Text(
value,
style: theme.textTheme.titleSmall
?.copyWith(fontFeatures: const [FontFeature.tabularFigures()]),
),
],
);
}
}
@@ -1,25 +1,37 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:iperf3gui/data/services/iperf3_service.dart'; import 'package:iperf3gui/domain/models/iperf3_event.dart';
import 'package:iperf3gui/domain/models/iperf3_result.dart'; import 'package:iperf3gui/domain/models/iperf3_result.dart';
import 'package:iperf3gui/domain/models/iperf3_session.dart';
import 'package:iperf3gui/domain/models/test_configuration.dart'; import 'package:iperf3gui/domain/models/test_configuration.dart';
import 'package:iperf3gui/domain/services/iperf3_runner.dart';
import 'package:iperf3gui/ui/features/test_run/iperf3_event_formatter.dart';
/// State of the test run. /// State of the test run.
enum TestRunState { idle, running, completed, error } enum TestRunState { idle, running, completed, error }
/// ViewModel for managing test run state. /// ViewModel for managing test run state.
/// ///
/// Subscribes to [Iperf3Service.outputLines] so the transcript grows while the /// Presentation only. What happened during a run is accumulated by
/// test runs rather than appearing all at once at the end. /// [Iperf3Session] in the domain layer; this class subscribes to
/// [Iperf3Runner.events], feeds that session, keeps a formatted transcript for
/// display, and decides when to repaint.
class TestRunViewModel extends ChangeNotifier { class TestRunViewModel extends ChangeNotifier {
final Iperf3Service iperf3Service; final Iperf3Runner iperf3Service;
/// How often to notify listeners while output is arriving. iperf3 can report
/// several times a second across many streams, and each rebuild re-renders
/// the whole transcript — so repaints are coalesced instead of one per event.
static const Duration displayInterval = Duration(milliseconds: 250);
TestRunViewModel({required this.iperf3Service}) { TestRunViewModel({required this.iperf3Service}) {
_outputSubscription = iperf3Service.outputLines.listen(_onOutputLine); _eventSubscription = iperf3Service.events.listen(_onEvent);
} }
StreamSubscription<String>? _outputSubscription; StreamSubscription<Iperf3Event>? _eventSubscription;
Timer? _repaintTimer;
bool _dirty = false;
TestRunState _state = TestRunState.idle; TestRunState _state = TestRunState.idle;
TestRunState get state => _state; TestRunState get state => _state;
@@ -30,11 +42,16 @@ class TestRunViewModel extends ChangeNotifier {
TestConfiguration? _currentConfig; TestConfiguration? _currentConfig;
TestConfiguration? get currentConfig => _currentConfig; TestConfiguration? get currentConfig => _currentConfig;
final StringBuffer _liveOutput = StringBuffer(); final StringBuffer _transcript = StringBuffer();
/// Output accumulated so far. Grows line by line during a run, and holds the /// Human-readable output accumulated so far. Display only — the structured
/// finished transcript once the test completes. /// record of the run is [session].
String get output => _liveOutput.toString(); String get output => _transcript.toString();
final Iperf3Session _session = Iperf3Session();
/// The accumulated run: interval series, totals, errors and their statistics.
Iperf3Session get session => _session;
/// Whether a test is currently in flight. /// Whether a test is currently in flight.
bool get isRunning => _state == TestRunState.running; bool get isRunning => _state == TestRunState.running;
@@ -47,35 +64,32 @@ class TestRunViewModel extends ChangeNotifier {
if (_state == TestRunState.running) return; if (_state == TestRunState.running) return;
if (!config.isValid) { if (!config.isValid) {
_liveOutput _resetRunData();
..clear() _transcript
..writeln('Invalid configuration: check the server address and port.'); .writeln('Invalid configuration: check the server address and port.');
_state = TestRunState.error; _state = TestRunState.error;
_result = null;
notifyListeners(); notifyListeners();
return; return;
} }
_resetRunData();
_state = TestRunState.running; _state = TestRunState.running;
_currentConfig = config; _currentConfig = config;
_result = null;
_liveOutput.clear();
notifyListeners(); notifyListeners();
try { try {
final result = await iperf3Service.run(config); final result = await iperf3Service.run(config);
_result = result; _result = result;
// Prefer the streamed transcript — it is what the user watched build up. if (_transcript.isEmpty && result.rawOutput.isNotEmpty) {
// Fall back to the service's copy if nothing streamed through. _transcript.write(result.rawOutput);
if (_liveOutput.isEmpty && result.rawOutput.isNotEmpty) {
_liveOutput.write(result.rawOutput);
} }
_state = _state =
result.exitCode == 0 ? TestRunState.completed : TestRunState.error; result.exitCode == 0 ? TestRunState.completed : TestRunState.error;
} catch (e) { } catch (e) {
_liveOutput.writeln('Test failed: $e'); _transcript.writeln('Test failed: $e');
_state = TestRunState.error; _state = TestRunState.error;
} finally { } finally {
_stopRepaintTimer();
notifyListeners(); notifyListeners();
} }
} }
@@ -88,21 +102,49 @@ class TestRunViewModel extends ChangeNotifier {
/// Reset to idle state. /// Reset to idle state.
void reset() { void reset() {
_resetRunData();
_state = TestRunState.idle; _state = TestRunState.idle;
_result = null;
_currentConfig = null; _currentConfig = null;
_liveOutput.clear();
notifyListeners(); notifyListeners();
} }
void _onOutputLine(String line) { void _resetRunData() {
_liveOutput.write(line.endsWith('\n') ? line : '$line\n'); _result = null;
_transcript.clear();
_session.clear();
_dirty = false;
}
void _onEvent(Iperf3Event event) {
_session.add(event);
final line = formatIperf3Event(event);
if (line != null && line.isNotEmpty) {
_transcript.writeln(line);
}
_scheduleRepaint();
}
/// Coalesce repaints: mark dirty and let a timer flush at [displayInterval].
void _scheduleRepaint() {
_dirty = true;
_repaintTimer ??= Timer.periodic(displayInterval, (_) {
if (!_dirty) return;
_dirty = false;
notifyListeners(); notifyListeners();
});
}
void _stopRepaintTimer() {
_repaintTimer?.cancel();
_repaintTimer = null;
_dirty = false;
} }
@override @override
void dispose() { void dispose() {
_outputSubscription?.cancel(); _stopRepaintTimer();
_eventSubscription?.cancel();
iperf3Service.dispose(); iperf3Service.dispose();
super.dispose(); super.dispose();
} }
+1 -1
View File
@@ -2,7 +2,7 @@ name: iperf3gui
description: "A Flutter-based Android GUI wrapper for iperf3." description: "A Flutter-based Android GUI wrapper for iperf3."
publish_to: 'none' publish_to: 'none'
version: 1.0.0+1 version: 0.1.0+1
environment: environment:
sdk: ^3.13.1 sdk: ^3.13.1
+144
View File
@@ -0,0 +1,144 @@
// Enforces the layering. A convention nobody checks is a convention that
// decays, so these read the real import statements in lib/ and fail on a
// violation rather than trusting review to catch it.
//
// The rule, in one line: dependencies point inward. ui → domain ← data, and
// never the reverse.
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('layering', () {
test('domain imports no Flutter at all', () {
final offenders = _importsMatching(
'lib/domain',
(import) => import.startsWith('package:flutter/'),
);
expect(
offenders,
isEmpty,
reason: 'The domain layer must stay pure Dart so it can be reused '
'without a Flutter runtime. Offending imports:\n'
'${_render(offenders)}',
);
});
test('domain does not depend on data or ui', () {
final offenders = _importsMatching(
'lib/domain',
(import) =>
import.contains('/data/') ||
import.contains('/ui/') ||
import.contains('main.dart'),
);
expect(offenders, isEmpty,
reason: 'The domain layer is the innermost layer; it may depend on '
'nothing else in this package.\n${_render(offenders)}');
});
test('data does not depend on ui', () {
final offenders = _importsMatching(
'lib/data',
(import) => import.contains('/ui/') || import.contains('main.dart'),
);
expect(offenders, isEmpty,
reason: 'The data layer must not know about presentation.\n'
'${_render(offenders)}');
});
test('data imports no Flutter widget libraries', () {
// flutter/services is allowed: MethodChannel lives there, and that is
// the whole reason this layer is Flutter-aware at all.
const allowed = {'package:flutter/services.dart'};
final offenders = _importsMatching(
'lib/data',
(import) =>
import.startsWith('package:flutter/') && !allowed.contains(import),
);
expect(
offenders,
isEmpty,
reason: 'The data layer may import package:flutter/services.dart only. '
'Anything else drags presentation into the transport.\n'
'${_render(offenders)}',
);
});
test('ui does not depend on a concrete data implementation', () {
// The UI talks to Iperf3Runner. main.dart is the composition root and is
// the one file allowed to name an implementation.
final offenders = _importsMatching(
'lib/ui',
(import) => import.contains('/data/'),
);
expect(
offenders,
isEmpty,
reason: 'Presentation must depend on domain/services/iperf3_runner.dart '
'rather than on a transport. Only main.dart may pick an '
'implementation.\n${_render(offenders)}',
);
});
test('the headless entry point does not depend on ui', () {
// main_headless.dart is the standing proof that the core runs without a
// widget tree; an import from lib/ui would quietly end that.
final offenders = _importsMatching(
'lib',
(import) => import.contains('/ui/'),
onlyFiles: {'lib/main_headless.dart'},
);
expect(
offenders,
isEmpty,
reason: 'The headless entry point must run the core with no UI.\n'
'${_render(offenders)}',
);
});
test('every layer directory is actually covered by these rules', () {
// Guards against a new top-level layer appearing and silently escaping
// every rule above.
final layers = Directory('lib')
.listSync()
.whereType<Directory>()
.map((d) => d.path.split(Platform.pathSeparator).last)
.toSet();
expect(
layers,
equals({'domain', 'data', 'ui'}),
reason: 'A new layer appeared under lib/. Add rules for it here.',
);
});
});
}
/// Every `(file, import)` pair under [directory] whose import satisfies [test].
List<({String file, String import})> _importsMatching(
String directory,
bool Function(String import) test, {
Set<String>? onlyFiles,
}) {
final results = <({String file, String import})>[];
final dir = Directory(directory);
if (!dir.existsSync()) return results;
final pattern = RegExp(r'''^\s*import\s+['"]([^'"]+)['"]''', multiLine: true);
for (final entity in dir.listSync(recursive: true)) {
if (entity is! File || !entity.path.endsWith('.dart')) continue;
if (onlyFiles != null && !onlyFiles.contains(entity.path)) continue;
final source = entity.readAsStringSync();
for (final match in pattern.allMatches(source)) {
final import = match.group(1)!;
if (test(import)) {
results.add((file: entity.path, import: import));
}
}
}
return results;
}
String _render(List<({String file, String import})> offenders) =>
offenders.map((o) => ' ${o.file} → ${o.import}').join('\n');
+107
View File
@@ -0,0 +1,107 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:iperf3gui/domain/models/iperf3_event.dart';
void main() {
group('Iperf3Event.parse', () {
test('parses a start event', () {
const line = '{"event":"start","data":{'
'"connecting_to":{"host":"192.168.2.182","port":5201},'
'"test_start":{"protocol":"TCP","num_streams":4,"duration":10}}}';
final event = Iperf3Event.parse(line);
expect(event, isA<Iperf3Start>());
final start = event as Iperf3Start;
expect(start.targetHost, equals('192.168.2.182'));
expect(start.targetPort, equals(5201));
expect(start.streamCount, equals(4));
expect(start.durationSeconds, equals(10));
expect(start.protocol, equals('TCP'));
});
test('parses an interval event with per-stream detail', () {
const line = '{"event":"interval","data":{'
'"streams":[{"socket":143,"bytes":49283072,'
'"bits_per_second":394264576.0,"retransmits":0,"snd_cwnd":2023424,'
'"rtt":3521}],'
'"sum":{"start":0.0,"end":1.000151,"seconds":1.000151,'
'"bytes":98566144,"bits_per_second":788410352.0,"retransmits":0,'
'"omitted":false,"sender":true}}}';
final event = Iperf3Event.parse(line);
expect(event, isA<Iperf3Interval>());
final interval = event as Iperf3Interval;
expect(interval.bytes, equals(98566144));
expect(interval.bitsPerSecond, closeTo(788410352.0, 0.1));
expect(interval.retransmits, equals(0));
expect(interval.omitted, isFalse);
expect(interval.streams, hasLength(1));
expect(interval.streams.single.socket, equals(143));
expect(interval.streams.single.rtt, equals(3521));
});
test('marks omitted intervals', () {
const line = '{"event":"interval","data":{"streams":[],'
'"sum":{"start":0.0,"end":1.0,"bytes":1,"bits_per_second":8.0,'
'"omitted":true}}}';
final interval = Iperf3Event.parse(line) as Iperf3Interval;
expect(interval.omitted, isTrue);
});
test('parses an end event with sent and received totals', () {
const line = '{"event":"end","data":{'
'"sum_sent":{"seconds":10.0,"bytes":987654321,'
'"bits_per_second":790123456.0,"retransmits":7},'
'"sum_received":{"seconds":10.01,"bytes":987000000,'
'"bits_per_second":789000000.0},'
'"cpu_utilization_percent":{"host_total":12.5,"remote_total":3.25}}}';
final end = Iperf3Event.parse(line) as Iperf3End;
expect(end.sent!.bytes, equals(987654321));
expect(end.sent!.retransmits, equals(7));
expect(end.received!.bitsPerSecond, closeTo(789000000.0, 0.1));
expect(end.hostCpuPercent, closeTo(12.5, 0.01));
expect(end.remoteCpuPercent, closeTo(3.25, 0.01));
});
test('falls back to bidir-reverse keys when present', () {
const line = '{"event":"interval","data":{"streams":[],'
'"sum_bidir_reverse":{"start":0.0,"end":1.0,"bytes":42,'
'"bits_per_second":336.0}}}';
final interval = Iperf3Event.parse(line) as Iperf3Interval;
expect(interval.bytes, equals(42));
});
test('parses an error event', () {
const line = '{"event":"error","data":"unable to connect to server"}';
final event = Iperf3Event.parse(line);
expect(event, isA<Iperf3Error>());
expect((event as Iperf3Error).message,
equals('unable to connect to server'));
});
test('parses the bridge stop marker', () {
final event = Iperf3Event.parse('{"event":"jni_stopped","data":{}}');
expect(event, isA<Iperf3Stopped>());
});
test('surfaces non-JSON output as a log line rather than dropping it', () {
final event = Iperf3Event.parse('iperf3: something unexpected');
expect(event, isA<Iperf3LogLine>());
expect((event as Iperf3LogLine).text,
equals('iperf3: something unexpected'));
});
test('surfaces malformed JSON as a log line', () {
final event = Iperf3Event.parse('{"event":"interval",');
expect(event, isA<Iperf3LogLine>());
});
test('treats an unknown event name as a log line', () {
final event = Iperf3Event.parse('{"event":"future_thing","data":{}}');
expect(event, isA<Iperf3LogLine>());
});
test('tolerates a missing data object', () {
final event = Iperf3Event.parse('{"event":"interval"}');
expect(event, isA<Iperf3Interval>());
expect((event as Iperf3Interval).bytes, equals(0));
});
});
}
+135
View File
@@ -0,0 +1,135 @@
// Pure-Dart tests for the run aggregate. No widgets, no bindings, no channel —
// this is the part that has to be correct regardless of what draws it.
import 'package:flutter_test/flutter_test.dart';
import 'package:iperf3gui/domain/models/iperf3_event.dart';
import 'package:iperf3gui/domain/models/iperf3_session.dart';
void main() {
Iperf3Interval sample(double start, double bits,
{int bytes = 1000, int? retransmits, bool omitted = false}) =>
Iperf3Interval(
start: start,
end: start + 1,
bytes: bytes,
bitsPerSecond: bits,
retransmits: retransmits,
omitted: omitted,
);
group('Iperf3Session', () {
test('starts empty', () {
final session = Iperf3Session();
expect(session.isEmpty, isTrue);
expect(session.sampleCount, isZero);
expect(session.intervals, isEmpty);
expect(session.start, isNull);
expect(session.summary, isNull);
expect(session.errors, isEmpty);
expect(session.stopped, isFalse);
expect(session.hasError, isFalse);
});
test('statistics are null before any sample', () {
final session = Iperf3Session();
expect(session.latestBitsPerSecond, isNull);
expect(session.meanBitsPerSecond, isNull);
expect(session.peakBitsPerSecond, isNull);
expect(session.totalRetransmits, isNull);
});
test('records start, intervals and summary', () {
final session = Iperf3Session()
..add(const Iperf3Start(targetHost: 'host', targetPort: 5201))
..add(sample(0, 100))
..add(const Iperf3End(
sent: Iperf3Total(seconds: 1, bytes: 10, bitsPerSecond: 80),
));
expect(session.isEmpty, isFalse);
expect(session.start!.targetHost, equals('host'));
expect(session.sampleCount, equals(1));
expect(session.summary!.sent!.bitsPerSecond, equals(80));
});
test('excludes omitted warm-up intervals from the series', () {
final session = Iperf3Session()
..add(sample(0, 10, omitted: true))
..add(sample(1, 100))
..add(sample(2, 200));
expect(session.sampleCount, equals(2));
expect(session.meanBitsPerSecond, equals(150),
reason: 'the omitted 10 would have pulled the mean to ~103');
});
test('computes mean, peak and latest over the samples', () {
final session = Iperf3Session()
..add(sample(0, 100))
..add(sample(1, 400))
..add(sample(2, 250));
expect(session.latestBitsPerSecond, equals(250));
expect(session.peakBitsPerSecond, equals(400));
expect(session.meanBitsPerSecond, equals(250));
});
test('sums sampled bytes', () {
final session = Iperf3Session()
..add(sample(0, 1, bytes: 1500))
..add(sample(1, 1, bytes: 2500));
expect(session.sampledBytes, equals(4000));
});
test('sums retransmits when reported', () {
final session = Iperf3Session()
..add(sample(0, 1, retransmits: 2))
..add(sample(1, 1, retransmits: 5));
expect(session.totalRetransmits, equals(7));
});
test('retransmits stay null when never reported, not zero', () {
// UDP reports no retransmit counts; "not measured" must not read as 0.
final session = Iperf3Session()
..add(sample(0, 1))
..add(sample(1, 1));
expect(session.totalRetransmits, isNull);
});
test('collects errors in order and flags them', () {
final session = Iperf3Session()
..add(const Iperf3Error('first'))
..add(const Iperf3Error('second'));
expect(session.hasError, isTrue);
expect(session.errors, equals(['first', 'second']));
expect(session.isEmpty, isFalse);
});
test('records a stop', () {
final session = Iperf3Session()..add(const Iperf3Stopped());
expect(session.stopped, isTrue);
});
test('ignores log lines', () {
final session = Iperf3Session()..add(const Iperf3LogLine('noise'));
expect(session.isEmpty, isTrue);
});
test('clear returns it to the empty state', () {
final session = Iperf3Session()
..add(const Iperf3Start(targetHost: 'host'))
..add(sample(0, 100))
..add(const Iperf3Error('boom'))
..add(const Iperf3Stopped())
..add(const Iperf3End())
..clear();
expect(session.isEmpty, isTrue);
expect(session.stopped, isFalse);
expect(session.hasError, isFalse);
expect(session.peakBitsPerSecond, isNull);
});
test('exposed collections are unmodifiable', () {
final session = Iperf3Session()..add(sample(0, 1));
expect(() => session.intervals.add(sample(1, 1)), throwsUnsupportedError);
expect(() => session.errors.add('x'), throwsUnsupportedError);
});
});
}
+62
View File
@@ -0,0 +1,62 @@
import 'dart:async';
import 'package:iperf3gui/domain/models/iperf3_event.dart';
import 'package:iperf3gui/domain/models/iperf3_result.dart';
import 'package:iperf3gui/domain/models/test_configuration.dart';
import 'package:iperf3gui/domain/services/iperf3_runner.dart';
/// In-memory [Iperf3Runner] for tests.
///
/// Implements the interface rather than the concrete service, so it tracks the
/// five members the UI actually depends on instead of every public member the
/// MethodChannel implementation happens to have.
class FakeIperf3Runner implements Iperf3Runner {
FakeIperf3Runner({this.onRun});
/// Supplies the result for each [run], and may [emit] events first.
Future<Iperf3Result> Function(TestConfiguration)? onRun;
final StreamController<Iperf3Event> _controller =
StreamController<Iperf3Event>.broadcast();
/// Configurations passed to [run], in order.
final List<TestConfiguration> runCalls = [];
int stopCallCount = 0;
bool disposed = false;
bool _isRunning = false;
int get runCallCount => runCalls.length;
/// Push an event as if the native layer had reported it.
void emit(Iperf3Event event) => _controller.add(event);
@override
Stream<Iperf3Event> get events => _controller.stream;
@override
bool get isRunning => _isRunning;
@override
Future<Iperf3Result> run(TestConfiguration config) async {
runCalls.add(config);
_isRunning = true;
try {
if (onRun != null) return await onRun!(config);
return const Iperf3Result(rawOutput: '', exitCode: 0);
} finally {
_isRunning = false;
}
}
@override
Future<void> stop() async {
stopCallCount++;
}
@override
Future<void> dispose() async {
disposed = true;
await _controller.close();
}
}
@@ -0,0 +1,87 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:iperf3gui/domain/models/iperf3_event.dart';
import 'package:iperf3gui/ui/features/test_run/iperf3_event_formatter.dart';
void main() {
group('formatBytes', () {
test('scales in binary units the way iperf3 prints totals', () {
expect(formatBytes(0), equals('0.00 Bytes'));
expect(formatBytes(1024), equals('1.00 KBytes'));
expect(formatBytes(98566144), equals('94.0 MBytes'));
expect(formatBytes(1073741824), equals('1.00 GBytes'));
});
});
group('formatBitrate', () {
test('scales in decimal units, as network rates are quoted', () {
expect(formatBitrate(0), equals('0.00 bits/sec'));
expect(formatBitrate(8000), equals('8.00 Kbits/sec'));
expect(formatBitrate(790000000), equals('790 Mbits/sec'));
expect(formatBitrate(2500000000), equals('2.50 Gbits/sec'));
});
});
group('formatIperf3Event', () {
test('renders a start event', () {
const event = Iperf3Start(
targetHost: '192.168.2.182',
targetPort: 5201,
protocol: 'TCP',
streamCount: 1,
durationSeconds: 10,
);
final text = formatIperf3Event(event)!;
expect(text, contains('Connecting to host 192.168.2.182, port 5201'));
expect(text, contains('TCP'));
expect(text, contains('1 stream'));
});
test('renders an interval with retransmits', () {
const event = Iperf3Interval(
start: 0,
end: 1,
bytes: 98566144,
bitsPerSecond: 788410352,
retransmits: 3,
);
final text = formatIperf3Event(event)!;
expect(text, contains('0.00-1.00 sec'));
expect(text, contains('94.0 MBytes'));
expect(text, contains('788 Mbits/sec'));
expect(text, contains('3 retr'));
});
test('marks an omitted interval', () {
const event = Iperf3Interval(
start: 0, end: 1, bytes: 1, bitsPerSecond: 8, omitted: true);
expect(formatIperf3Event(event), contains('omitted'));
});
test('renders sender and receiver lines from an end event', () {
const event = Iperf3End(
sent: Iperf3Total(
seconds: 10, bytes: 987654321, bitsPerSecond: 790000000,
retransmits: 7),
received: Iperf3Total(
seconds: 10.01, bytes: 987000000, bitsPerSecond: 789000000),
hostCpuPercent: 12.5,
);
final text = formatIperf3Event(event)!;
expect(text, contains('sender'));
expect(text, contains('receiver'));
expect(text, contains('7 retr'));
expect(text, contains('CPU: local 12.5%'));
});
test('renders errors and stops', () {
expect(formatIperf3Event(const Iperf3Error('boom')),
equals('iperf3 error: boom'));
expect(formatIperf3Event(const Iperf3Stopped()),
equals('Stopped by user.'));
});
test('drops an empty log line', () {
expect(formatIperf3Event(const Iperf3LogLine('')), isNull);
});
});
}
@@ -1,15 +1,17 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:iperf3gui/data/services/iperf3_service.dart'; import 'package:iperf3gui/domain/models/iperf3_event.dart';
import 'package:iperf3gui/domain/models/iperf3_result.dart'; import 'package:iperf3gui/domain/models/iperf3_result.dart';
import 'package:iperf3gui/domain/models/test_configuration.dart'; import 'package:iperf3gui/domain/models/test_configuration.dart';
import 'package:iperf3gui/ui/features/test_run/test_run_view_model.dart'; import 'package:iperf3gui/ui/features/test_run/test_run_view_model.dart';
import '../../../support/fake_iperf3_runner.dart';
void main() { void main() {
group('TestRunViewModel', () { group('TestRunViewModel', () {
test('starts in idle state', () { test('starts in idle state', () {
final vm = TestRunViewModel(iperf3Service: _MockIperf3Service()); final vm = TestRunViewModel(iperf3Service: FakeIperf3Runner());
expect(vm.state, equals(TestRunState.idle)); expect(vm.state, equals(TestRunState.idle));
expect(vm.result, isNull); expect(vm.result, isNull);
expect(vm.currentConfig, isNull); expect(vm.currentConfig, isNull);
@@ -17,13 +19,13 @@ void main() {
}); });
test('can be reset', () { test('can be reset', () {
final vm = TestRunViewModel(iperf3Service: _MockIperf3Service()); final vm = TestRunViewModel(iperf3Service: FakeIperf3Runner());
vm.reset(); vm.reset();
expect(vm.state, equals(TestRunState.idle)); expect(vm.state, equals(TestRunState.idle));
}); });
test('invalid config sets error state without running', () async { test('invalid config sets error state without running', () async {
final mock = _MockIperf3Service(); final mock = FakeIperf3Runner();
final vm = TestRunViewModel(iperf3Service: mock); final vm = TestRunViewModel(iperf3Service: mock);
const config = TestConfiguration(server: ''); const config = TestConfiguration(server: '');
await vm.runTest(config); await vm.runTest(config);
@@ -32,7 +34,7 @@ void main() {
}); });
test('runTest with valid config calls service', () async { test('runTest with valid config calls service', () async {
final mock = _MockIperf3Service( final mock = FakeIperf3Runner(
onRun: (config) async { onRun: (config) async {
expect(config.server, equals('192.168.1.1')); expect(config.server, equals('192.168.1.1'));
return const Iperf3Result(rawOutput: 'done', exitCode: 0); return const Iperf3Result(rawOutput: 'done', exitCode: 0);
@@ -46,7 +48,7 @@ void main() {
}); });
test('non-zero exit code lands in error state', () async { test('non-zero exit code lands in error state', () async {
final mock = _MockIperf3Service( final mock = FakeIperf3Runner(
onRun: (_) async => onRun: (_) async =>
const Iperf3Result(rawOutput: 'boom', exitCode: 1), const Iperf3Result(rawOutput: 'boom', exitCode: 1),
); );
@@ -56,11 +58,16 @@ void main() {
expect(vm.result!.exitCode, equals(1)); expect(vm.result!.exitCode, equals(1));
}); });
test('streamed lines accumulate into output during the run', () async { test('streamed events accumulate into output during the run', () async {
final mock = _MockIperf3Service(); final mock = FakeIperf3Runner();
mock.onRun = (_) async { mock.onRun = (_) async {
mock.emit('Connecting to host 192.168.1.1\n'); mock.emit(const Iperf3Start(targetHost: '192.168.1.1', targetPort: 5201));
mock.emit('[ 5] 0.00-1.00 sec 11.2 MBytes 94.1 Mbits/sec\n'); mock.emit(const Iperf3Interval(
start: 0,
end: 1,
bytes: 11744051,
bitsPerSecond: 94100000,
));
// Let the broadcast stream deliver before the run resolves. // Let the broadcast stream deliver before the run resolves.
await Future<void>.delayed(Duration.zero); await Future<void>.delayed(Duration.zero);
return const Iperf3Result(rawOutput: 'ignored', exitCode: 0); return const Iperf3Result(rawOutput: 'ignored', exitCode: 0);
@@ -69,14 +76,51 @@ void main() {
final vm = TestRunViewModel(iperf3Service: mock); final vm = TestRunViewModel(iperf3Service: mock);
await vm.runTest(const TestConfiguration(server: '192.168.1.1')); await vm.runTest(const TestConfiguration(server: '192.168.1.1'));
expect(vm.output, contains('Connecting to host')); expect(vm.output, contains('Connecting to host 192.168.1.1'));
expect(vm.output, contains('94.1 Mbits/sec')); expect(vm.output, contains('94.1 Mbits/sec'));
// The streamed transcript wins over the service's own copy. // The streamed transcript wins over the service's own copy.
expect(vm.output, isNot(contains('ignored'))); expect(vm.output, isNot(contains('ignored')));
}); });
test('events are fed into the session', () async {
final mock = FakeIperf3Runner();
mock.onRun = (_) async {
mock.emit(const Iperf3Interval(
start: 0, end: 1, bytes: 1000, bitsPerSecond: 8000));
mock.emit(const Iperf3End(
sent: Iperf3Total(seconds: 1, bytes: 1000, bitsPerSecond: 8000),
));
await Future<void>.delayed(Duration.zero);
return const Iperf3Result(rawOutput: '', exitCode: 0);
};
final vm = TestRunViewModel(iperf3Service: mock);
await vm.runTest(const TestConfiguration(server: '192.168.1.1'));
expect(vm.session.sampleCount, equals(1));
expect(vm.session.summary, isNotNull);
});
test('a new run clears the previous session', () async {
final mock = FakeIperf3Runner();
mock.onRun = (_) async {
mock.emit(const Iperf3Interval(
start: 0, end: 1, bytes: 1000, bitsPerSecond: 8000));
await Future<void>.delayed(Duration.zero);
return const Iperf3Result(rawOutput: '', exitCode: 0);
};
final vm = TestRunViewModel(iperf3Service: mock);
await vm.runTest(const TestConfiguration(server: '192.168.1.1'));
expect(vm.session.sampleCount, equals(1));
await vm.runTest(const TestConfiguration(server: '192.168.1.1'));
expect(vm.session.sampleCount, equals(1),
reason: 'not appended to the old run');
});
test('falls back to result output when nothing streamed', () async { test('falls back to result output when nothing streamed', () async {
final mock = _MockIperf3Service( final mock = FakeIperf3Runner(
onRun: (_) async => onRun: (_) async =>
const Iperf3Result(rawOutput: 'summary only', exitCode: 0), const Iperf3Result(rawOutput: 'summary only', exitCode: 0),
); );
@@ -86,7 +130,7 @@ void main() {
}); });
test('output is cleared when a new run starts', () async { test('output is cleared when a new run starts', () async {
final mock = _MockIperf3Service( final mock = FakeIperf3Runner(
onRun: (_) async => onRun: (_) async =>
const Iperf3Result(rawOutput: 'first', exitCode: 0), const Iperf3Result(rawOutput: 'first', exitCode: 0),
); );
@@ -102,7 +146,7 @@ void main() {
}); });
test('stopTest forwards to the service only while running', () async { test('stopTest forwards to the service only while running', () async {
final mock = _MockIperf3Service(); final mock = FakeIperf3Runner();
final vm = TestRunViewModel(iperf3Service: mock); final vm = TestRunViewModel(iperf3Service: mock);
await vm.stopTest(); await vm.stopTest();
@@ -121,7 +165,7 @@ void main() {
}); });
test('wasStopped reflects a user-requested stop', () async { test('wasStopped reflects a user-requested stop', () async {
final mock = _MockIperf3Service( final mock = FakeIperf3Runner(
onRun: (_) async => const Iperf3Result( onRun: (_) async => const Iperf3Result(
rawOutput: 'stopped early', rawOutput: 'stopped early',
exitCode: 0, exitCode: 0,
@@ -136,7 +180,7 @@ void main() {
}); });
test('wasStopped is false for a run that finished on its own', () async { test('wasStopped is false for a run that finished on its own', () async {
final mock = _MockIperf3Service( final mock = FakeIperf3Runner(
onRun: (_) async => onRun: (_) async =>
const Iperf3Result(rawOutput: 'done', exitCode: 0), const Iperf3Result(rawOutput: 'done', exitCode: 0),
); );
@@ -146,7 +190,7 @@ void main() {
}); });
test('a second runTest while running is ignored', () async { test('a second runTest while running is ignored', () async {
final mock = _MockIperf3Service(); final mock = FakeIperf3Runner();
final gate = Completer<Iperf3Result>(); final gate = Completer<Iperf3Result>();
mock.onRun = (_) => gate.future; mock.onRun = (_) => gate.future;
@@ -160,49 +204,3 @@ void main() {
}); });
}); });
} }
class _MockIperf3Service implements Iperf3Service {
_MockIperf3Service({this.onRun});
Future<Iperf3Result> Function(TestConfiguration)? onRun;
final StreamController<String> _controller =
StreamController<String>.broadcast();
int runCallCount = 0;
int stopCallCount = 0;
bool disposed = false;
bool _isRunning = false;
/// Push a line as if the native layer had emitted it.
void emit(String line) => _controller.add(line);
@override
Stream<String> get outputLines => _controller.stream;
@override
bool get isRunning => _isRunning;
@override
Future<Iperf3Result> run(TestConfiguration config) async {
runCallCount++;
_isRunning = true;
try {
if (onRun != null) return await onRun!(config);
return const Iperf3Result(rawOutput: '', exitCode: 0);
} finally {
_isRunning = false;
}
}
@override
Future<void> stop() async {
stopCallCount++;
}
@override
Future<void> dispose() async {
disposed = true;
await _controller.close();
}
}
+78 -6
View File
@@ -1,17 +1,89 @@
// This is a basic Flutter widget test. // Widget-level smoke tests.
// //
// To perform an interaction with a widget in your test, use the WidgetTester // These drive the real UI against a FakeIperf3Runner: no MethodChannel, no
// utility in the flutter_test package. For example, you can send tap and scroll // native library, no device. That is only possible because the presentation
// gestures. You can also use WidgetTester to find child widgets in the widget // layer depends on the Iperf3Runner interface rather than on Iperf3Service.
// tree, read text, and verify that the values of widget properties are correct.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:iperf3gui/domain/models/iperf3_event.dart';
import 'package:iperf3gui/domain/models/iperf3_result.dart';
import 'package:iperf3gui/main.dart'; import 'package:iperf3gui/main.dart';
import 'support/fake_iperf3_runner.dart';
void main() { void main() {
testWidgets('App smoke test', (WidgetTester tester) async { testWidgets('App smoke test', (WidgetTester tester) async {
await tester.pumpWidget(const Iperf3GuiApp()); await tester.pumpWidget(Iperf3GuiApp(runner: FakeIperf3Runner()));
expect(find.text('iperf3-gui'), findsOneWidget); expect(find.text('iperf3-gui'), findsOneWidget);
expect(find.text('GO'), findsOneWidget);
expect(find.text('Ready'), findsOneWidget);
});
testWidgets('runs a test and renders streamed results', (tester) async {
final runner = FakeIperf3Runner();
runner.onRun = (config) async {
runner.emit(Iperf3Start(
targetHost: config.server,
targetPort: config.port,
protocol: 'TCP',
streamCount: config.parallelStreams,
));
runner.emit(const Iperf3Interval(
start: 0,
end: 1,
bytes: 98566144,
bitsPerSecond: 788410352,
));
await Future<void>.delayed(Duration.zero);
return const Iperf3Result(rawOutput: '', exitCode: 0);
};
await tester.pumpWidget(Iperf3GuiApp(runner: runner));
await tester.tap(find.text('GO'));
await tester.pumpAndSettle();
expect(runner.runCallCount, equals(1));
expect(find.text('Test complete'), findsOneWidget);
expect(find.textContaining('788 Mbits/sec'), findsWidgets);
// The stat row is driven by the parsed interval series.
expect(find.text('peak'), findsOneWidget);
});
testWidgets('shows a stop button while running and can stop', (tester) async {
final runner = FakeIperf3Runner();
final gate = Completer<Iperf3Result>();
runner.onRun = (_) => gate.future;
await tester.pumpWidget(Iperf3GuiApp(runner: runner));
await tester.tap(find.text('GO'));
await tester.pump();
expect(find.text('STOP'), findsOneWidget);
expect(find.text('Running…'), findsOneWidget);
await tester.tap(find.text('STOP'));
await tester.pump();
expect(runner.stopCallCount, equals(1));
gate.complete(const Iperf3Result(
rawOutput: '', exitCode: 0, stopped: true));
await tester.pumpAndSettle();
expect(find.text('Stopped'), findsOneWidget);
});
testWidgets('rejects an empty server address', (tester) async {
final runner = FakeIperf3Runner();
await tester.pumpWidget(Iperf3GuiApp(runner: runner));
await tester.enterText(find.byType(TextField).first, '');
await tester.tap(find.text('GO'));
await tester.pumpAndSettle();
expect(runner.runCallCount, equals(0));
expect(find.textContaining('Invalid configuration'), findsOneWidget);
}); });
} }