Skip to content

Telemetry collector development and deployment ​

WARNING: This page was generated by a generative AI, info may be wrong.

This page is for developers operating or changing the telemetry collector. For what AudioX collects, privacy details, and enabling or disabling collection, see the user telemetry guide.

Report schema and sampling ​

After consent, the main control loop samples one point per completed 10-second interval, including while the WebUI is closed. There is no telemetry code in the realtime audio callback. Partial intervals across restarts are not reported; long sampling gaps reset the interval instead of inventing missing points.

Each point contains:

  • public_consent: 1 in schema 3 only, after the user accepts public aggregates.
  • A random 256-bit installation_id (64 lowercase hex characters) and interval_ms: 10000, plus a separate random 128-bit point ID for deduplication.
  • Firmware version and Pi family (4, 5, or unknown 0).
  • Physical ALSA card counts: USB audio interfaces, USB gadget, and other ALSA audio cards (including onboard audio). Multiple PCM endpoints on one card count once. Unusual hardware exposing several ALSA cards can still count more than once.
  • Connected Bluetooth audio peer count, input/output-capable device counts, and whether the currently supported MIDI connection is present (0 or 1, not a comprehensive inventory of every MIDI device attached).
  • Soundboard-trigger, MIDI note/CC event, scene-recall and X-run counter deltas. These reflect existing application counters, not a complete record of every physical key press or successfully audible clip. Sampler mode is a snapshot.
  • Engine sample rate and processing block size; latest whole-degree temperature and whole-percent CPU utilization, or null when unavailable. CPU is the latest short-interval sample, not the average over the whole 10 seconds.
  • Effect counts as [configured, enabled] pairs, in this fixed order: gain, distortion, pitch, reverb, gate, cut, compressor, limiter, EQ, multiband compressor, noise reduction, then one combined bucket for Advanced EQ, Bass Enhancer, Crossfeed, Maximizer, and third-party plugins. Enabled does not mean routed, audible, or actually processed.

No names, Bluetooth addresses, USB vendor/product/serial identities, stable hardware hashes, audio, filenames, script contents, scene names, or raw logs are included. The installation ID is generated with the kernel random source on opt-in, persisted across restarts, and removed on opt-out. Re-enabling creates a new ID. Cloning the data partition copies the ID; this is not hardware identity or a guaranteed count of physical devices. Do not copy it into distributable images. Firmware version is the build version; do not put private information in custom version strings.

Cloudflare necessarily receives connection IP addresses and browser/network metadata. The Worker does not store them in D1 or log request contents. Its transient per-IP abuse limiter is separate from application reporting. These are minimized/pseudonymous reports, not a guarantee of absolute anonymity.

Idle filtering ​

The first point is retained. Subsequent points are skipped only when no audio activity, soundboard triggers, MIDI note/CC events, scene recalls or X-runs are observed and the device/effect/sampler/routing/gain state is unchanged. CPU/temperature fluctuations alone do not preserve an idle point. Effect/graph/device generation changes catch parameter/routing/device changes even when the exported counts are identical; gain maps are compared at interval boundaries. Retained points keep their counters; there is no averaging or merging. Existing cloud rows are not deleted by this filter.

The control loop samples existing peak meters at approximately -90 dBFS and soundboard playback state throughout the interval, latching observed activity. This keeps steady audio even if all configuration snapshots are identical. It is a best-effort observation, not an audio-thread activity counter: bursts between polls or below threshold may be missed. Never infer exact audible duration from it. Exported metrics.audio_active is 0 or 1.

Queue and delivery ​

The device appends small records to its persistent data partition and syncs once per retained point. The queue survives restarts and holds at most 8,640 points (about 24 hours of continuous activity; longer when idle). At capacity, it drops the oldest 100 before accepting another point and logs a warning. A corrupt/unreadable queue stops collection and upload and exposes an error; disable and re-enable telemetry to clear it.

While the real WebUI is open, it checks once per minute and starts draining the backlog whenever at least 100 are pending. Each request carries up to 1,000 points; consecutive requests include the final smaller remainder. Thus 120 or 500 points upload in one request. A fresh 99-point queue waits until another point arrives, but an in-progress cycle retries a failed smaller remainder without a page reload. Short sessions can accumulate across reboots. Browser background throttling, suspension and lack of internet can delay upload.

The browser sends HTTPS directly to https://telemetry.audiox.wklab.net/v1/batches, then acknowledges that exact batch to the Pi only after receiving a matching collector receipt. Failed uploads retain the queue and back off from one minute to one hour. Retried requests or multiple browser tabs are deduplicated by point ID in the database. Opt-out is checked again before transmission; a cross-tab opt-out cannot recall a request already in flight.

Acknowledgements remove only the matching queue prefix, preserving points collected while a request was in flight. Each batch has a 30-second timeout. One cycle drains the starting backlog rather than running indefinitely as new points arrive. A full 8,640-point queue requires nine requests, within the single-browser 10-request/minute ingestion limit; competing tabs/clients can still be rate-limited and retry later.

Use Preview next upload (local only) to inspect a ready batch without sending it. The raw queue is also local; no cloud request is made just by viewing its status or preview.

With two continuously active installations, collection produces up to 17,280 points/day and roughly 173 batch uploads/day. No port forwarding is required, and the Pi does not need internet access. Only the computer displaying the WebUI needs internet for delivery. If nobody opens the WebUI, nothing uploads.

Collector protocol ​

The /v1/batches endpoint accepts 1-1,000 points in schema 3 batches. Reports include installation_id, interval_ms, metrics.audio_active, and public_consent: 1. Point fields are stored in the payload JSON; public aggregates use the public_daily and public_dashboard tables.

The device requires consent_version=3 when enabling telemetry. Users must accept the public-reporting notice before reports can be uploaded.

Deploy the collector on Cloudflare ​

The collector source is in tools/telemetry/. It uses a Worker, one D1 database, and a Worker Custom Domain. Your registrar can remain elsewhere: what matters is that wklab.net is an active zone in your Cloudflare account, with its assigned Cloudflare nameservers.

These are operator steps; AudioX does not deploy infrastructure automatically. Keep Cloudflare tokens and account credentials out of the repository and device. Use the free Workers plan initially and check the dashboard's usage/limits. Plan availability and quotas can change: Workers limits, D1 pricing.

1. Install the deployment tool and log in ​

Run on your development computer, not on the Pi:

sh
cd tools/telemetry
npm ci
npx wrangler login
npx wrangler whoami

The browser login must select the account containing the active wklab.net zone. No domain transfer, home server, router change, or port forwarding is needed.

2. Create and initialize D1 ​

sh
npx wrangler d1 create audiox-telemetry

Copy the returned database UUID into database_id in wrangler.jsonc, replacing REPLACE_WITH_DATABASE_ID. Leave the binding named DB. The UUID is not an API credential.

sh
npx wrangler d1 migrations apply audiox-telemetry --remote

The migrations create a private points table and retention index plus precomputed public aggregate tables. Raw reports never have a public read route.

3. Attach your hostname and deploy ​

The checked-in configuration already declares:

json
"routes": [
  { "pattern": "telemetry.audiox.wklab.net", "custom_domain": true }
]

Ensure this exact hostname is unused; do not point it at your home IP or manually create a CNAME to workers.dev. Do not remove unrelated DNS records. If it already has a record, inspect that record and resolve the conflict first.

sh
npm run deploy

Cloudflare creates/manages the Custom Domain DNS record and certificate. In Workers & Pages > audiox-telemetry > Settings > Domains & Routes, verify telemetry.audiox.wklab.net is active, including certificate provisioning. This is a Worker Custom Domain, not a route to an existing origin server. If adding it through the dashboard instead, use Add > Custom Domain. See Cloudflare Custom Domains.

sh
curl --fail --show-error https://telemetry.audiox.wklab.net/health

Expected: {"service":"audiox-telemetry","schema":3}. Wait for DNS/certificate activation if needed; do not disable certificate validation.

workers.dev and preview URLs are disabled. Public routes are the health check, write-only batch ingestion, dashboard assets, and /api/public/summary for precomputed aggregate JSON. Raw database browsing stays inside your Cloudflare account.

4. Verify CORS and the first real upload ​

sh
curl --include --request OPTIONS \
  https://telemetry.audiox.wklab.net/v1/batches \
  --header 'Origin: http://audiox.local' \
  --header 'Access-Control-Request-Method: POST' \
  --header 'Access-Control-Request-Headers: content-type'

Expected: status 204, Access-Control-Allow-Origin: http://audiox.local, and allowed method/header values. The configured allowlist also covers the stock USB IP and documented alternate AudioX hostnames. If you use another local address or a development port, add its exact origin to ALLOWED_ORIGINS and redeploy. Do not use wildcard origins.

Install the firmware and open the WebUI. Choose Enable telemetry, leave AudioX actively processing audio or receiving usage events for at least 100 completed 10-second intervals (16 minutes 40 seconds), then inspect System. With internet available, the pending backlog should drain after the next browser check. Do not lower the threshold or send synthetic production rows just to test it: the local tests cover the 99/100-point boundary.

If uploads fail, check the System telemetry status, browser Network panel, hostname certificate and CORS allowlist. Plain HTTP local UI to public HTTPS ingestion is supported; HTTPS pages fetching a local HTTP device would be a different mixed-content scenario.

5. View your data privately ​

Use Storage & databases > D1 > audiox-telemetry > Console in Cloudflare, or:

sh
npx wrangler d1 execute audiox-telemetry --remote \
  --command "SELECT received_day, COUNT(*) AS retained_points FROM points GROUP BY received_day ORDER BY received_day DESC"
sh
npx wrangler d1 execute audiox-telemetry --remote \
  --command "SELECT json_extract(payload, '$.version') AS version, COUNT(*) AS points FROM points GROUP BY version"
sh
npx wrangler d1 execute audiox-telemetry --remote \
  --command "SELECT received_day, SUM(json_extract(payload, '$.metrics.soundboard_triggers')) AS soundboard_triggers, SUM(json_extract(payload, '$.metrics.xruns')) AS xruns FROM points GROUP BY received_day ORDER BY received_day DESC"
sh
npx wrangler d1 execute audiox-telemetry --remote \
  --command "SELECT json_extract(payload, '$.effects[3][1]') AS enabled_reverbs, COUNT(*) AS points FROM points GROUP BY enabled_reverbs"

received_day is the collector's UTC receipt date, not the collection date. The device may have been offline and has no guaranteed accurate wall clock. Points describe retained 10-second intervals, not a complete uptime history; idle intervals are omitted. They do not measure precise audible-processing duration. Use each report's interval_ms when summing observed time.

Filter and group reports by installation using the JSON field:

sh
npx wrangler d1 execute audiox-telemetry --remote \
  --command "SELECT json_extract(payload, '$.installation_id') AS installation_id, COUNT(*) AS retained_points, SUM(json_extract(payload, '$.interval_ms')) / 1000 AS observed_interval_seconds FROM points GROUP BY installation_id"
sh
npx wrangler d1 execute audiox-telemetry --remote \
  --command "SELECT received_day, payload FROM points WHERE json_extract(payload, '$.installation_id') = 'REPLACE_WITH_64_HEX_ID' ORDER BY received_day DESC, id LIMIT 100"

Legacy reports form a NULL group; it is not one installation. Point IDs are random and received_day has only date precision, so this ordering groups receipt days, not the original sampling order within a day. Installation IDs change on opt-out/re-enable or reinstallation, and cloned storage can share one, so they are not reliable unique-user or physical-device counts.

Retention, privacy and abuse ​

An hourly scheduled job deletes rows received 30 or more UTC dates ago. Reports can remain until that hour's cleanup runs. This application-level deletion is not immediate erasure from Cloudflare-managed backups/Time Travel or provider connection metadata; review Cloudflare's policies for those.

There is no public raw-report read endpoint or shared API secret in the WebUI. The collector strictly validates fields, values, a 2 MiB body limit, and bounded batch sizes, and applies an approximate 10-request/minute per-IP limit. Rate limiter namespace 1001 must be unique among your account's rate limiter definitions; change it if you already use it.

CORS is a browser restriction, not authentication. A determined client can forge its Origin and submit fabricated usage. Do not treat reports as trusted measurements, use them for billing, or assume these limits stop quota exhaustion. For a small voluntary project this is intentionally a public ingestion service; monitor usage and disable the Worker if abused. Avoid enabling paid usage without reviewing billing safeguards. Do not add a Cloudflare Access login to the ingestion route unless you also redesign the browser upload flow.

Worker request logging is disabled in configuration. Do not enable body/header logging, analytics enrichment with IP/geolocation, or wrangler tail request capture without revisiting the privacy notice. Any future private raw-report dashboard needs its own authenticated read path; do not expose D1 publicly.

Public graphs and aggregate API ​

After deployment, visit https://telemetry.audiox.wklab.net/. The same Worker serves bundled static assets; no separate Pages project, chart CDN, public D1 credential, or browser database access is needed. The dashboard renders SVG charts, bar charts and a daily table, including an explicit empty/error state. The read-only GET /api/public/summary endpoint can also be fetched by another public website (its aggregate JSON permits wildcard CORS without credentials). The ingestion origin allowlist is separate and remains restricted.

The hourly cron (17 * * * *) first prunes expired raw reports, then rebuilds current/yesterday's daily statistics, retaining older daily aggregates for the 30-day window. On first run it scans the available 30-day window. Indexed receipt-day bounds avoid rescanning the entire raw history every hour thereafter. A singleton snapshot combines the fixed daily rows; public requests read only that snapshot, never points. Browser caching lasts five minutes. A missing snapshot returns 503 until the first scheduled refresh; a snapshot over two hours old returns an explicit delayed-refresh error instead of serving stale data indefinitely.

Only points carrying schema 3's validated public_consent: 1 qualify. The server builds an explicit allowlist of numeric aggregates and UTC receipt dates. No raw payloads, point IDs, installation IDs, exact version strings, exact event times, installation counts or per-installation filters are returned. The API rejects query parameters and offers no SQL, date-range or grouping parameters. Firmware distribution deliberately uses broad version-string families, not exact custom versions that could carry identifiers. CPU/temperature means ignore unavailable values, device/effect charts show observation-weighted averages, and counters show sums. These are not unique devices/users, total uptime, or precise audible durations.

No minimum population is enforced, as chosen for this two-installation project. Even daily totals may reveal individual activity. The consent popup and user guide disclose this; do not describe the public data as anonymous. Copies made by visitors cannot be recalled. Keep schemas 1/2 private even if an old installation previously opted into telemetry; the older notice did not cover public reporting. Opt-out deletes local data/ID, not uploaded/public history.

The snapshot and daily aggregate tables expire with the same rolling receipt window. Provider backups have separate retention. If manually deleting private source reports for a privacy request, also remove/rebuild affected public daily rows and the snapshot; source deletion alone does not update older aggregates. There is intentionally no public refresh/admin endpoint.

Verify the public page ​

Apply migrations before deploy, then wait for the hourly cron at minute 17:

sh
curl --fail https://telemetry.audiox.wklab.net/api/public/summary

The response contains format, updated_at, and 30 days. Before any renewed consents upload, zero observations are expected; do not mark older reports as public to populate the charts. Check Workers & Pages > audiox-telemetry > Settings > Trigger Events if the hourly refresh does not run. Snapshot refresh errors are surfaced as failed scheduled invocations and public 503 responses.

For local scheduled-event testing, use local-only bindings (remove any remote: true bindings from a temporary local config), run wrangler dev --test-scheduled, and call http://localhost:8787/__scheduled. Never trigger tests against the production database or submit synthetic reports to the public collector.

Development checks ​

From the repository root:

sh
make test-usage-telemetry
node --test tests/web/telemetry_test.js tools/telemetry/worker.test.js

The collector can be exercised against local D1 without creating production data:

sh
cd tools/telemetry
npx wrangler d1 migrations apply audiox-telemetry --local
npx wrangler dev

To change the hostname, update both the Worker route and browser endpoint, plus the privacy copy and this guide. A schema expansion that changes privacy scope must use a new consent version and re-prompt, rather than silently broadening an existing opt-in.

AudioX is open source and under active development.