Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,15 @@ All notable changes to MeterX are documented here. The format follows [Keep a Ch
### Added
- Support links: "Support on Ko-fi" in the site footer and the extension's options page (plain links, nothing new loads), and a Support section in the README with Ko-fi and a UPI QR code

### Changed
- Upload streams resize each body from how long the last one took, aiming at about 1 s per request, so a test makes far fewer server requests and the free quota covers several times more tests

### Fixed
- Tests run from a private or incognito window are no longer saved to history; the result still shows (#97)
- Chrome and Edge uploads stalled on some networks (seen on Jio): Chrome used HTTP/3 to the test server, and uploads over it hung until the test gave up. The default test server is now `meterx-api.ajithakdev.com`, served without HTTP/3. The extension asks for access to the new address once; the old `workers.dev` address keeps working for older versions
- Upload read about half of the real speed in Chrome on fast lines (BSNL 60/60: 14 to 29 Mbps against curl's 55 to 66), because Chrome sends uploads over HTTP/2 slowly. Uploads now go to the worker's `workers.dev` address over HTTP/3 and read 53 to 66 Mbps on the same line. If an upload request there fails, or a stream's first upload stays open over 3 s as on Jio, the upload phase starts again on `meterx-api.ajithakdev.com` (#104)
- Upload read far too low, or failed with "No data reached the server", on lines with a much slower upload than download (for example Jio 5G: 124 Mbps down, about 4 up). The first upload body was sized from the download speed and could not finish in time; every stream now starts at 256 KB and grows from what it measures (#60)
- The worker serves `/ping` as a static asset, which Cloudflare does not count against the free plan's 100,000 requests a day. About 35 of a test's 150 requests are pings, so the same quota now covers about 30% more tests, with no extension update. An A/B test on 2026-11-21 showed the same ping times. Downloads stay on the Worker: as static assets, each request waited about 180 ms longer for its first byte
- A custom server URL typed with a trailing slash (`https://host/`) failed every test with 404s; Settings now tidies it before testing and saving (#68)

## [2027.0.2] - 2026-10-31
Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,6 @@ Custom server URLs need a runtime host-permission grant (`optional_host_permissi

- The version lives only in the root `package.json`. `@meterx/shared` exports it as `VERSION` (used by `/health`, the exports and the settings footer), and `build.mjs` stamps it into `dist/manifest.json`, so it must be 1 to 4 dot-separated numbers. Bump that one line to release.
- `manifest.json` description must stay within the store's 132-character limit.
- Store packages: Chromium stores share one zip; Firefox gets a converted manifest (sidebar, background script, id `meterx@ajithakdev`). The default worker URL is `WORKER_URL` in shared, and also sits in `host_permissions` in the extension's `static/manifest.json` and the site's `static/_headers` CSP; change all three together.
- Store packages: Chromium stores share one zip; Firefox gets a converted manifest (sidebar, background script, id `meterx@ajithakdev`). The default worker URL is `WORKER_URL` in shared, and also sits in `host_permissions` in the extension's `static/manifest.json` and the site's `static/_headers` CSP; change all three together. `WORKER_H3_URL` (the same worker on workers.dev, which keeps HTTP/3) is where uploads go first; it is in `host_permissions` too, and the site never uploads so its CSP leaves it out.
- Nothing deploys on merge. The worker (`wrangler deploy`), the site (Pages direct upload, not git-connected) and the stores are released by hand on Sunday, so docs-only merges are just merges.
- License is AGPL-3.0; see `TRADEMARK.md` before touching branding.
5 changes: 3 additions & 2 deletions RESOURCES-AND-GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Every link for MeterX, what it is for, and how to run, package and release it. P
- Code: https://github.com/ajithakdev/meterx (was `meterx-server`; GitHub redirects the old URL)
- `npm run build`, `npm test`, `npm run lint` from the root; `npm run package` writes the store uploads to `release/`.
- Releases are weekly on Sunday: tag, GitHub release, `wrangler deploy` for the worker, store uploads, site deploy.
- Default test server: https://meterx-speedtest.meterx-ajithakdev.workers.dev
- Default test server: https://meterx-api.ajithakdev.com

## Links and what each one is for

Expand All @@ -24,7 +24,8 @@ Every link for MeterX, what it is for, and how to run, package and release it. P
| https://addons.mozilla.org/firefox/addon/meterx-by-ajithakdev/ | Firefox listing (add-on id `meterx@ajithakdev`), 2027.0.1 live since 2026-10-27 |
| https://microsoftedge.microsoft.com/addons/detail/glkpolbkpachomgmmhdkmjnghejbhlfc | Microsoft Edge listing (2027.0.1 in review from 2026-10-27) |
| Opera Add-ons | Not public yet: 2027.0.1 awaiting moderation (slug `meterx-by-ajithakdev-2`). Add the link to `apps/site/src/stores.ts` and the README once it's public |
| https://meterx-speedtest.meterx-ajithakdev.workers.dev | Default test server (Cloudflare Worker) |
| https://meterx-api.ajithakdev.com | Default test server (Cloudflare Worker), HTTP/2 only |
| https://meterx-speedtest.meterx-ajithakdev.workers.dev | Same worker with HTTP/3: uploads go here first and fall back to meterx-api if a request fails or the first one stalls |
| https://ko-fi.com/ajithakdev | Tips. Linked from the README, the site footer and the extension options page |

### Behind the scenes
Expand Down
25 changes: 13 additions & 12 deletions apps/extension/src/background/measure.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { toMbps, bytesAtTime, steadyMbps, median, latencyStats, gradeBufferbloat, uploadChunkBytes, backoffMs } from './measure';
import { toMbps, bytesAtTime, steadyMbps, median, latencyStats, gradeBufferbloat, nextUploadChunk, backoffMs } from './measure';

const opts = { rampMs: 1000, tailMs: 500, durationMs: 8000 };

Expand Down Expand Up @@ -64,17 +64,18 @@ describe('gradeBufferbloat', () => {
});
});

describe('uploadChunkBytes', () => {
it('uses small bodies on slow links so requests finish (#60)', () => {
expect(uploadChunkBytes(10, 3)).toBe(256 * 1024);
expect(uploadChunkBytes(undefined, 3)).toBe(256 * 1024);
});
it('caps bodies on fast links', () => {
expect(uploadChunkBytes(5000, 3)).toBe(8 * 1024 * 1024);
});
it('targets about 4 completions per second per stream', () => {
// 300 Mbps over 3 streams = 12.5 MB/s per stream, quarter of that per body.
expect(uploadChunkBytes(300, 3)).toBe(3_125_000);
describe('nextUploadChunk', () => {
it('sizes the next body to take about 1 s', () => {
expect(nextUploadChunk(1_000_000, 250)).toBe(4_000_000);
expect(nextUploadChunk(2_000_000, 2000)).toBe(1_000_000);
});
it('grows at most 4x per request, so a slow uplink still completes bodies (#60)', () => {
expect(nextUploadChunk(300_000, 10)).toBe(1_200_000);
expect(nextUploadChunk(300_000, 0)).toBe(1_200_000);
});
it('stays within the min and max body sizes', () => {
expect(nextUploadChunk(256 * 1024, 5000)).toBe(256 * 1024);
expect(nextUploadChunk(8 * 1024 * 1024, 100)).toBe(8 * 1024 * 1024);
});
});

Expand Down
22 changes: 12 additions & 10 deletions apps/extension/src/background/measure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,19 +55,21 @@ export function latencyStats(latencies: number[], attempts: number): { ping: num


const KB = 1024;
const MIN_UPLOAD_CHUNK = 256 * KB;
const MAX_UPLOAD_CHUNK = 8 * 1024 * KB;
/** Every upload stream starts here and grows from what it measures, so lopsided lines (fast down, slow up) still finish bodies (#60). */
export const MIN_UPLOAD_CHUNK = 256 * KB;
export const MAX_UPLOAD_CHUNK = 8 * 1024 * KB;

const UPLOAD_TARGET_MS = 1000;

/**
* Upload body size so each stream finishes about 4 requests a second.
* Bytes only count when a request completes, so fixed 5 MB bodies read
* 0 Mbps on slow uplinks (#60). Sized from the download speed, which is
* known by then and is usually the higher of the two.
* Next body size for one upload stream, from how long its last body took: aims at about
* 1 s per request, so a test spends about 24 Worker requests on uploads instead of about 96.
* Grows at most 4x per step, so a slow uplink behind a fast downlink still completes bodies (#60).
*/
export function uploadChunkBytes(downloadMbps: number | undefined, streams: number): number {
const perStreamBytesPerSec = ((downloadMbps || 0) * 1e6) / 8 / Math.max(1, streams);
const target = Math.round(perStreamBytesPerSec / 4);
return Math.min(MAX_UPLOAD_CHUNK, Math.max(MIN_UPLOAD_CHUNK, target));
export function nextUploadChunk(lastBytes: number, lastMs: number): number {
const ideal = lastMs > 0 ? (lastBytes * UPLOAD_TARGET_MS) / lastMs : lastBytes * 4;
const next = Math.round(Math.min(ideal, lastBytes * 4));
return Math.min(MAX_UPLOAD_CHUNK, Math.max(MIN_UPLOAD_CHUNK, next));
}

/** Delay before retrying a failed transfer request: 250 ms, doubling, capped at 2 s (#65). */
Expand Down
89 changes: 89 additions & 0 deletions apps/extension/src/background/runner.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { WORKER_H3_URL, WORKER_URL } from '@meterx/shared';
import { CancelledError, runTest } from './runner';

// Fake clock and fetch: every request settles after a fake delay, so a whole test runs in milliseconds.
type UploadDelay = (h3: boolean, n: number) => number | 'hang' | 429;

function mockServer(uploadDelay: UploadDelay) {
const uploads = { h3: 0, h2: 0 };
vi.stubGlobal('fetch', vi.fn((url: string, init: RequestInit = {}) => {
let ms = 50;
let status = 200;
let body: BodyInit | null = null;
if (url.includes('/upload')) {
const h3 = url.startsWith(WORKER_H3_URL);
const d = uploadDelay(h3, h3 ? ++uploads.h3 : ++uploads.h2);
if (d === 429) status = 429;
else ms = d === 'hang' ? -1 : d;
} else if (url.includes('/test-file')) body = new Uint8Array(64 * 1024);
else if (url.includes('/ip')) body = '{}';
const signal = init.signal;
return new Promise<Response>((resolve, reject) => {
if (signal?.aborted) return reject(signal.reason);
const abort = () => { clearTimeout(t); reject(signal!.reason); };
const t = ms < 0 ? undefined : setTimeout(() => {
signal?.removeEventListener('abort', abort);
resolve(new Response(body, { status }));
}, ms);
signal?.addEventListener('abort', abort, { once: true });
});
}));
return uploads;
}

beforeEach(() => {
vi.useFakeTimers();
vi.spyOn(performance, 'now').mockImplementation(() => Date.now());
vi.spyOn(AbortSignal, 'timeout').mockImplementation(ms => {
const c = new AbortController();
setTimeout(() => c.abort(new DOMException('timed out', 'TimeoutError')), ms);
return c.signal;
});
});

afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});

async function run(signal = new AbortController().signal) {
const result = runTest(WORKER_URL, signal, () => {});
result.catch(() => {}); // awaited below; stops an unhandled-rejection warning while time advances
await vi.advanceTimersByTimeAsync(40_000);
return result;
}

describe('upload over HTTP/3 with HTTP/2 fallback (#104)', () => {
it('falls back to the HTTP/2 address when the first HTTP/3 body stalls', async () => {
const uploads = mockServer(h3 => (h3 ? 'hang' : 200));
const r = await run();
expect(uploads.h2).toBeGreaterThan(0);
expect(r.uploadSpeed).toBeGreaterThan(0);
});

it('stays on HTTP/3 when a later request is slow', async () => {
const uploads = mockServer((h3, n) => (h3 && n > 3 ? 5000 : 200));
const r = await run();
expect(uploads.h2).toBe(0);
expect(r.uploadSpeed).toBeGreaterThan(0);
});

it('falls back when HTTP/3 answers with an error', async () => {
const uploads = mockServer(h3 => (h3 ? 429 : 200));
const r = await run();
expect(uploads.h2).toBeGreaterThan(0);
expect(r.uploadSpeed).toBeGreaterThan(0);
});

it('a cancel during the HTTP/3 attempt does not fall back', async () => {
const ctrl = new AbortController();
const uploads = mockServer(h3 => {
if (h3) setTimeout(() => ctrl.abort(), 500);
return h3 ? 'hang' : 200;
});
await expect(run(ctrl.signal)).rejects.toBeInstanceOf(CancelledError);
expect(uploads.h2).toBe(0);
});
});
65 changes: 48 additions & 17 deletions apps/extension/src/background/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@

/// <reference types="chrome" />

import type { IpInfo, TestProgress, TestResults } from '@meterx/shared';
import { WORKER_H3_URL, WORKER_URL, type IpInfo, type TestProgress, type TestResults } from '@meterx/shared';
import {
type ByteSample, backoffMs, bytesAtTime, gradeBufferbloat, latencyStats,
median, steadyMbps, toMbps, uploadChunkBytes,
median, nextUploadChunk, steadyMbps, toMbps, MAX_UPLOAD_CHUNK, MIN_UPLOAD_CHUNK,
} from './measure';

const DOWNLOAD_PATH = '/test-file/25MB.bin';
const DOWNLOAD_STREAMS = 4;
const UPLOAD_STREAMS = 3;
/** A stream whose first upload is still open after 3 s has stalled (HTTP/3 on Jio). Later requests have no limit, so a brief dip can't trigger it; a stream under about 0.7 Mbps up does, harmlessly. */
const UPLOAD_STALL_MS = 3000;
// Multi-stream, fixed-duration phases (the M-Lab / Ookla approach).
// The worker and Express rate limits are sized for this burst; raise them if you add streams.
const MEASURE_DURATION_MS = 8000;
Expand Down Expand Up @@ -76,7 +78,7 @@ function startLoadedProbe(baseUrl: string, signal: AbortSignal): () => Promise<n
async function runStreams(
signal: AbortSignal,
streams: number,
one: (signal: AbortSignal, credit: (bytes: number) => void) => Promise<void>,
one: (signal: AbortSignal, credit: (bytes: number) => void, stream: number) => Promise<void>,
onLive: (mbps: number) => void,
): Promise<number> {
const phase = new AbortController();
Expand All @@ -100,11 +102,11 @@ async function runStreams(
}
};

const loop = async () => {
const loop = async (stream: number) => {
let failures = 0;
while (!both.aborted) {
try {
await one(both, credit);
await one(both, credit, stream);
failures = 0;
} catch (e) {
if (both.aborted) break;
Expand All @@ -115,7 +117,7 @@ async function runStreams(
};

try {
await Promise.all(Array.from({ length: streams }, loop));
await Promise.all(Array.from({ length: streams }, (_, i) => loop(i)));
} finally {
clearTimeout(timer);
}
Expand Down Expand Up @@ -199,19 +201,48 @@ export async function runTest(baseUrl: string, signal: AbortSignal, report: Repo
report({ phase: 'download', downloadSpeed: results.downloadSpeed });

report({ phase: 'upload', status: 'Testing upload' });
const payload = new Uint8Array(uploadChunkBytes(results.downloadSpeed, UPLOAD_STREAMS));
stopProbe = startLoadedProbe(baseUrl, signal);
try {
results.uploadSpeed = await runStreams(signal, UPLOAD_STREAMS, async (s, credit) => {
const res = await fetch(bust(`${baseUrl}/upload`, 'u'), {
method: 'POST', cache: 'no-store', signal: s,
headers: { 'Content-Type': 'application/octet-stream' }, body: payload,
});
if (!res.ok) throw new HttpError(res.status);
await res.arrayBuffer();
const payload = new Uint8Array(MAX_UPLOAD_CHUNK);
const upload = (base: string, stallMs?: number) => {
// Each stream starts small and resizes its body from its own last request (see nextUploadChunk).
const chunkOf: number[] = Array(UPLOAD_STREAMS).fill(MIN_UPLOAD_CHUNK);
const stalled = new AbortController();
const settled: boolean[] = Array(UPLOAD_STREAMS).fill(false);
return runStreams(AbortSignal.any([signal, stalled.signal]), UPLOAD_STREAMS, async (s, credit, stream) => {
const body = payload.subarray(0, chunkOf[stream]);
const t0 = performance.now();
try {
const res = await fetch(bust(`${base}/upload`, 'u'), {
method: 'POST', cache: 'no-store',
signal: stallMs && !settled[stream] ? AbortSignal.any([s, AbortSignal.timeout(stallMs)]) : s,
headers: { 'Content-Type': 'application/octet-stream' }, body,
});
if (!res.ok) throw new HttpError(res.status);
await res.arrayBuffer();
} catch (e) {
if (stallMs && !s.aborted) stalled.abort();
throw e;
}
// fetch() has no upload progress, so bytes count when each body completes.
credit(payload.byteLength);
credit(body.byteLength);
settled[stream] = true;
chunkOf[stream] = nextUploadChunk(body.byteLength, performance.now() - t0);
}, mbps => report({ phase: 'upload', uploadSpeed: mbps }));
};
stopProbe = startLoadedProbe(baseUrl, signal);
try {
// Chrome uploads over HTTP/2 read about half of a fast line, and over HTTP/3 they stall on some
// networks (Jio). The default server's uploads try its HTTP/3 address first; if any request there
// fails or a stream's first body takes over UPLOAD_STALL_MS, the phase starts again on the HTTP/2 address (#104).
if (baseUrl === WORKER_URL) {
try {
results.uploadSpeed = await upload(WORKER_H3_URL, UPLOAD_STALL_MS);
} catch (e) {
if (signal.aborted) throw e;
results.uploadSpeed = await upload(baseUrl);
}
} else {
results.uploadSpeed = await upload(baseUrl);
}
} finally {
results.loadedPingUp = await stopProbe();
}
Expand Down
1 change: 1 addition & 0 deletions apps/extension/static/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"sidePanel"
],
"host_permissions": [
"https://meterx-api.ajithakdev.com/*",
"https://meterx-speedtest.meterx-ajithakdev.workers.dev/*"
],
"optional_host_permissions": [
Expand Down
2 changes: 1 addition & 1 deletion apps/site/static/_headers
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=(), interest-cohort=()
Content-Security-Policy: default-src 'self'; connect-src 'self' https://meterx-speedtest.meterx-ajithakdev.workers.dev https://api.github.com; img-src 'self' data: https://avatars.githubusercontent.com; style-src 'self' 'unsafe-inline'; font-src 'self'; script-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'
Content-Security-Policy: default-src 'self'; connect-src 'self' https://meterx-api.ajithakdev.com https://api.github.com; img-src 'self' data: https://avatars.githubusercontent.com; style-src 'self' 'unsafe-inline'; font-src 'self'; script-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'
Strict-Transport-Security: max-age=31536000

/fonts/*
Expand Down
Loading
Loading