Author SHA1 Message Date
faumarayandClaude Fable 5.1 ba224e1dff Merge phase5/gpui-foundation: the foundation of the GPUI front end (Rust 1.95, ashpd on async-io with zbus on one executor, crates/voelin-gpui on gpui-kit 0.8.1, the root entity and the engine's event loop, VoelinTheme with Inter and Lucide, the meter)
CI / Linux checks (push) Successful in 1h10m33s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 15:22:04 +03:00
faumarayandClaude Sonnet 5.5 d84b54270c docs/design/gpui-spikes.md: the status paragraph records the foundation's review, gate and minors round
The report's status paragraph said the foundation landed and stopped there, and
that the figures on the page were still 0.8.0's. It now says the foundation was
reviewed and gated the same day (no blocker, no major, six minors), lists the
minors that are closed in the commits after it, points at docs/ui.md "For the
next slices" for the risks left to the slices, and excepts the two video cases
the review ran again on 0.8.1 from "still 0.8.0's".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 13:49:35 +03:00
faumarayandClaude Sonnet 5.5 2e22fd567c docs/media.md: the portal capture no longer needs a tokio runtime to start
The Portal note said `start` needs a tokio runtime because zbus runs on it. Since
the move of ashpd to `async-io` (e325b65) zbus runs every connection on an I/O
thread of its own, whichever thread builds it, and the note in portal.rs says
so (corrected in ed49c28); this record was not among the four the gate listed
and had been left behind. `stop` is the one that needs the runtime, and only to
close the portal session in the background (elsewhere the session closes with
the connection): the note now says both.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 13:49:15 +03:00
faumarayandClaude Sonnet 5.5 8f3d809e8a voelin-gpui: fonts.rs points at the report's "Open choices for step 3", which exist
The module comment sent the colour emoji to docs/design/gpui-spikes.md,
"Emoji", a section the report does not have (the colour emoji gap is a
paragraph of spike 2, and the choice is under "Open choices for step 3"): the
same dangling pointer docs/ui.md had in the slice 4 line, found by grep in the
round that fixed that one.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 13:49:15 +03:00
faumarayandClaude Sonnet 5.5 e5f8821f67 docs/ui.md: "For the next slices", the risks of the gate and the review; the report's quiet-machine figures
The risks the Opus gate and the review of the foundation left to the slices
that meet them, each with where it sits in the code: the engine-event task
drains its channel without yielding, the tick notifies the root every second,
voelin-platform's hotkey portal calls tokio::spawn (start it on the engine's
runtime as Slint's GlobalPtt::start does), PortalCapture::stop closes the
portal session only inside a tokio runtime, gpui-component's ThemeRegistry
observer overwrites VoelinTheme's mapping on any registry change, the parity
test and build.rs read crates/voelin-ui/ui (they move at step 9), system
mode's first frame is Light until the colour-scheme portal answers, the gate's
deviations from the report's mapping table (bg-rail not mapped, one scrim for
three, gpui-base's non-colour tokens not written), and the close grace not
seen end to end until a slice opens sessions.

docs/design/gpui-spikes.md: "the 1440p60 figures were not reproduced on
0.8.1" now carries the review's quiet-machine re-run of the two cases (static
61 fps, raw 59.1 fps, load average 8 to 12, llvmpipe).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:31:05 +03:00
faumarayandClaude Sonnet 5.5 5c94b15820 voelin-gpui: the parity test notices a second brush or string in theme.slint
The test compared the brush and string declarations of theme.slint by name
only (one backdrop, one font-family and the mode string), so a second brush or
string token in the Slint file passed unseen while docs/ui.md said a token on
one side only fails the test. It now asserts the brush declarations are
exactly {backdrop} and the strings exactly {mode, font-family}, and a test
adds a brush and a string to a copy of the file (a mutant) and checks both are
named: red with the previous rule ("backdrop-soft goes unnoticed"), green
with this one.

A Rust-only second brush or string is still not seen (tokens.rs has one
gradient and one family that the test cannot enumerate); docs/ui.md says so
instead of promising it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:29:02 +03:00
faumarayandClaude Sonnet 5.5 977b942cd0 docs/ui.md: slice 4 points at the report's "Open choices for step 3", which exist
The list of slices sent the chat slice to a section "Emoji" of
docs/design/gpui-spikes.md, which has none (the colour emoji gap is a
paragraph of spike 2). It now names the section "Open choices for step 3" and
the two open choices the chat slice touches there, emoji and links.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:26:45 +03:00
faumarayandClaude Sonnet 5.5 caf77561a9 about-assets.md: the Lucide 1.43 catalogue of gpui-kit-assets embedded in voelin-gpui
voelin-gpui embeds gpui-kit-assets' catalogue (Lucide 1.43.0, 1,818 icons,
beside 12 icons of the crate's own under its Apache-2.0 licence) behind the
client's own 1.48 set, and the notices named only the 1.48 set. The new line
has the same copyright holder, and the ISC and Feather MIT texts already
below are the catalogue's (its LICENSE-LUCIDE). THIRD_PARTY_NOTICES.md is
regenerated with scripts/notices.sh.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:26:17 +03:00
faumarayandClaude Sonnet 5.5 5af85b4aa2 docs/design/gpui-spikes.md: the lock figures of the foundation, 292 entries with their two sources
The size paragraph said gpui-kit adds 279 entries (208 new names) to
Cargo.lock. The foundation's lock has 1,321 entries against main's 1,029: 292,
218 of them new names. 279 come from gpui-kit and 13 from voelin-gpui's
`gpui-pre` `test-support` dev-dependency, which ships in no binary (the lock
without that line has 1,308 entries).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:25:04 +03:00
faumarayandClaude Sonnet 5.5 ed49c283a2 voelin-platform: zbus on async-io alone in every binary (notify-rust z), and a test for the order of ashpd's callers
ashpd 0.13.13 keeps one session connection per process (a static in its
proxy.rs), and zbus 5.19 picks that connection's executor once, from
Handle::try_current() on the thread that builds it, when both its `tokio` and
`async-io` features are compiled in. The first ashpd caller therefore decided
the executor of every later portal call: a tokio caller first, then a caller
with no runtime (a GPUI foreground task), panics with "there is no reactor
running" (get_property("version") sets up zbus's property cache, which calls
tokio::task::spawn). The merged binary was safe only because GPUI's
colour-scheme call builds the connection before the engine's portal calls.

voelin-platform's notify-rust asks for `z` (async-io) in place of
`z-with-tokio`, and the stand-in portal's zbus dev-dependency for `async-io`
instead of `tokio`: a test binary with both features shows the panic even when
the binaries do not have it. `cargo tree -e features -i zbus` now names
`tokio` nowhere; Cargo.lock loses zbus's tokio edge and tokio's tracing edge
(THIRD_PARTY_NOTICES.md is unchanged).

tests/proxy.rs gets the gate's probe shape on a private dbus-run-session bus
(skipped with a printed reason where none can be made): a tokio caller first,
then a caller with no runtime. It fails with the panic on the tree before this
change, and still did with only notify-rust moved, which is why the
dev-dependency moved too.

The four records that described the move wrongly are corrected:
docs/design/gpui-spikes.md "Dependencies", the comment of
PortalCapture::start, voelin-media's Cargo.toml and CHANGELOG.md (whose
Slint-only sentence goes: the Slint app's zbus connections move to async-io
threads too).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:24:19 +03:00
faumarayandClaude Sonnet 5.5 3f4dc700af voelin-gpui: the meter's /proc test waits for a CPU tick instead of burning 60 ms
this_process_can_be_read_on_linux burned CPU for 60 ms of wall time and
asserted that some thread group used a tick (10 ms) of it. On a busy machine
this thread gets less than a tick in 60 ms: with 5 busy loops on the test's
core, 39 of 40 runs failed at `!threads.is_empty()`. The test now burns CPU
until a second reading shows the process's tick count above the first and a
thread group above its own (a 30 s deadline only ends a hang, as
docs/testing/load.md asks), then asserts; 40 of 40 pass under the same
recipe (taskset to one core, 5 busy loops, 40 runs).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 12:19:30 +03:00
faumarayandClaude Sonnet 5.5 7cabc2c13d docs/ui.md: which of the GPUI tests need a display
The Tests bullet said the tests need no display and then named
tests/launch_failure.rs, one case of which starts the binary on the test
display of VOELIN_X11_TEST_DISPLAY (skipped without it, like the X11 tests of
voelin-media and voelin-platform); the other case needs no display at all.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 10:10:11 +03:00
faumarayandClaude Sonnet 5.5 d3fa8d85f0 docs: the spikes' README and report no longer put the repository on Rust 1.94
Since 5ce5c0d the repository is on 1.95.0, but spikes/gpui/README.md still
said no gpui-kit builds with "the repository's Rust 1.94" and the report's risk
table said "the client is on 1.94". The README now says the 1.94 the
repository used before 5ce5c0d (the E0658 demonstration with TOOLCHAIN=1.94
stays as the historical evidence), the risk row says the client moved to 1.95.0
in 5ce5c0d (seven lints fixed), and the report's "Settled for step 3" sentence
about the same failure names the 1.94 of before that commit too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:42:49 +03:00
faumarayandClaude Sonnet 5.5 6852204277 voelin-gpui: Later::run says what its answer promises
The doc said `false` "when the window is gone". The loop that drains the jobs
learns that the entity was released only when a job reaches it: the first job
sent after the release still answers `true` and is never run, and only the
next call is refused (a hotkey or decoder thread that calls run() after the
window went and before another job could so believe a job was queued that
never ran). The doc says that now ("false once a job has found the window
gone", true promises that the job was queued), and a test pins the order: the
job after the release is queued and never runs, the one after it is refused.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:42:21 +03:00
faumarayandClaude Sonnet 5.5 efc7db57a3 voelin-gpui: closing the window gives the engine time to send the session closes
The window's close sends CloseSession for every session (AppState::shutdown)
and ended the app straight into runtime.shutdown_timeout(2 s), which waits for
blocking tasks only and drops the engine's async tasks: the commands could go
with the runtime and leave ghost clients on the servers until they time out.
voelin-ui sleeps 500 ms in that case before shutting its runtime down
(app.rs after ui.run()); run() does the same now. shutdown() returns how many
sessions it told the engine to close, the close handler keeps that number for
run() (the App and its entities are gone once GPUI's loop has returned), and
run() waits CLOSE_GRACE only when it is not zero. A comment in run() tells the
slices that add another way to end the app to call shutdown() too.

The GPUI window cannot open a session in this slice, so the wait is not seen
end to end; the tests pin the count: with an engine a state holding a session
answers 1 and a state with none 0, without an engine 0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:42:10 +03:00
faumarayandClaude Sonnet 5.5 a4694e944b voelin-gpui: a window that cannot open ends the app with the reason, not a hang
When open_main_window failed (no usable Vulkan or GL driver), run() stored the
error and called cx.quit() inside the launch callback. GPUI's Linux platform
calls that callback before it starts its event loop, and calloop's
EventLoop::run clears its stop signal on entry, so the quit was lost: the
binary stayed alive with no window and no message (reproduced on a private
Xvfb with VK_DRIVER_FILES, __EGL_VENDOR_LIBRARY_DIRS and LIBGL_DRIVERS_PATH
pointing nowhere: exit 124 under `timeout`, nothing in the log after "Creating
colormap"), and the `failure` that main was to print was never returned. The
quit is a foreground task now, which runs inside the loop: the same run exits
with status 1 and "cannot open the main window / Failed to create surface".

With no display server at all GPUI starts its headless platform, whose
open_window succeeds with a window that draws nothing, so the same silent hang
came from there; open_main_window refuses a compositor named "headless" with
"no display: neither DISPLAY nor WAYLAND_DISPLAY names a display server".

tests/launch_failure.rs starts the built binary both ways (the driver case
under VOELIN_X11_TEST_DISPLAY, skipped where the machine's driver is found
anyway; the display case needs none) and fails when the process outlives two
minutes; with the old cx.quit() the driver test fails after 120 s, with the fix
both pass in a third of a second. docs/ui.md ("Running it") says what a missing
driver and a missing display look like; CHANGELOG.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 09:41:53 +03:00
faumarayandClaude Sonnet 5.5 97d51fb226 CI and docs: libxkbcommon-x11-dev and libxcb1-dev, which the GPUI front end links
The release binary of voelin-gpui links libxcb.so.1 and libxkbcommon-x11.so.0
(`readelf -d`: libxcb, libxkbcommon, libxkbcommon-x11, libasound, libm, libc)
and opens libwayland-client.so.0, libvulkan.so.1 and libEGL.so.1 by name
(`strings`). The development packages of the first two were in no package
list, so a workspace build on the Ubuntu runner (CI builds every member)
would have failed to link: .github/actions/system-deps, the CI example in
docs/ci.md, docker/linux.Dockerfile ("the same libraries as CI") and the apt
line of docs/building.md name libxkbcommon-x11-dev and libxcb1-dev now, and
building.md and docs/ui.md say what the GPUI front end links and what it
opens by name (an earlier sentence of mine had all of them opened by name).
Not run: no Ubuntu runner or image here; this machine builds with Nix's
libraries, where the headers come from the same projects.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 08:10:37 +03:00
faumarayandClaude Sonnet 5.5 d4f9e59ed6 scripts/gpui-shot.sh: ImageMagick 6 (convert, identify) where magick is not there
Debian and Ubuntu ship ImageMagick 6, which has no `magick`; the script now
uses `convert` and `identify` when `magick` is missing, and its header names
what it needs (xdotool, xwd, ImageMagick). Both branches were run on Xvfb
:98 (the second with a PATH that has `convert` and `identify` only): the
swatch picture is 1440x960 and the window closes with exit code 0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:47:36 +03:00
faumarayandClaude Sonnet 5.5 172d6247c6 docs: "The GPUI front end" in docs/ui.md, the spikes report's status and notes, README
docs/ui.md gains the section "The GPUI front end": what exists (the crate's
files and what each does), the root state and its three loops (the engine's
events through a foreground task, the one-second tick, Later for other
threads, and why Later exists: GPUI's AsyncApp is not Send), the tests and why
they use gpui-pre's test-support and not gpui-kit's, how to run it (what
GPUI needs at run time: Vulkan or OpenGL, lavapipe in software, a window
manager on X11), the development switches in a table, how the screenshots are
made (scripts/gpui-shot.sh, and the NixOS recipe over the spikes' headless
display) with the two swatch pictures, the theme in its two layers with the
mapping from the Voelin tokens to gpui-component's ThemeColor fields, the
mode, Inter and Lucide, and what is next: the plan's slices 1 to 9 with what
each takes from the Bridge, the conditions the spikes set (the emoji patch
before chat, a GPU run before the viewer, Wayland's preedit) and the steps
around them.

docs/design/gpui-spikes.md: the status paragraph says the foundation of step 3
landed (items 1 to 4 and 6 of its list; the shell is next) and points to
docs/ui.md; "Before step 3 can start" and "Dependencies" say the Rust move and
the ashpd move are done, with what zbus does with both features and the test
that calls ashpd with no tokio runtime; the size bullet gives what gpui-kit
adds to the root lock (279 entries, about 195 packages on Linux, two new
licences); a paragraph after the first slice's list says which items are done
and how.

README.md: the crate's bullet says what the window has so far.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:16:22 +03:00
faumarayandClaude Sonnet 5.5 a2fad4569a voelin-gpui: the backdrop's GPUI gradient in one place (Backdrop::to_gpui)
GPUI's gradient has two colour stops and the Slint backdrop three, so what
GPUI draws is the first and the last; that choice was written inline in the
swatch page. It is a method of the token now (theme/mod.rs), with a test that
it is the gradient of the first and the last stops and not of the middle one,
and the swatch calls it. No change on screen.

Checked on Rust 1.95.0: fmt, clippy -D warnings --no-deps (all targets),
`cargo test -p voelin-gpui` (31 tests).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:15:31 +03:00
faumarayandClaude Sonnet 5.5 109e1d1839 voelin-gpui: the cost meter as a development switch (VOELIN_METER=1), logged once a second
meter.rs is spike_common::meter of the GPUI spikes
(spikes/gpui/common/src/meter.rs, docs/design/gpui-spikes.md) without the
measuring run's summary and exit: once a second, on a thread of its own, a
log line (target voelin_gpui::meter, level info) with the process's CPU in
percent of one core, the resident memory, the CPU of each group of threads
(a thread's name without its trailing number: `llvmpipe-12` is `llvmpipe`,
which tells the software renderer's share, work a GPU would take, from
GPUI's thread, the engine's runtime and the codecs; the busiest first, groups
under 0.5 % left out), the app's own counters per second and the voice
connections as a gauge:

  cpu 11.9% rss 250.4 MiB | threads llvmpipe 5.9 voelin-gpui 5.0 |
  engine_events 0.0/s ticks 1.0/s renders 1.0/s later_jobs 0.0/s | connections 0

The counters (`Counters`: engine events handled, ticks, renders, jobs run
through `Later`, connections up) are shared with the root state and the main
view, which count in `handle_event`, `tick`, the later task and `render`; the
numbers come from /proc/self (a note and a warning say so where there is none;
rustix's `param` for the page size and the clock tick, Linux only, no new
package: the lock gains the edge). The line is a pure function with a test,
as are the thread grouping and the stat parser (a name with spaces and
parentheses), and one test reads this process and checks it has threads and
memory. The root state's tests now also check the counters (events, the
connection gauge, three ticks, a job from another thread).

`VOELIN_METER=1` starts it (dev.rs parses it with the other switches).
Running the debug binary on the swatch page on Xvfb :97 logs the lines above
(about 12 % of a core when idle, the software renderer 6 to 11 % of it, one
frame a second); the window closes with exit code 0. The default log filter
now leaves out GPUI's "failed to load font .SystemUIFont" warning, which
every start printed (gpui-component asks for the platform UI font before the
theme names Inter; the text system falls back).

Checked on Rust 1.95.0: fmt, clippy -D warnings --no-deps (all targets),
`cargo test -p voelin-gpui` (30 tests), cargo deny, `scripts/notices.sh
--check`.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:12:56 +03:00
faumarayandClaude Sonnet 5.5 2690b8a802 voelin-gpui: VoelinTheme (every token of theme.slint, light and dark) written into gpui-component, Inter, the client's Lucide icons, the swatch page
Two layers, as the spikes' report settled:
1. `VoelinTheme`, a GPUI global (theme/tokens.rs): the 43 colour tokens of
   ui/theme.slint for light and dark (generated from the Slint file by a
   script, then checked by the test below), the backdrop gradient, and
   `Metrics`: the radii, spacing, type sizes, weights, control and shell
   sizes and the two durations at a text size factor (font-scale: the
   sidebar's `264 * max(1, scale)` and the top bar's `max(44, control + 8)`
   included).
2. gpui-component's `ThemeColor`, written on every change (theme/components.rs):
   the base of the report's table (background, foreground, border, input,
   ring, overlay; primary with hover, active and foreground from the client's
   accent; secondary and muted from surface-2 and its raised steps;
   gpui-component's "accent", which is a hover background, from surface-3;
   popover; list, table, sidebar, title and status bar, tabs, switch, slider,
   scrollbar, link, selection; danger, success, warning and info with a hover
   and active made by mixing and a text that is white or the window's ink,
   whichever contrasts more) and the 28 `button_*` fields a theme file would
   derive from them (without them the buttons keep the default theme's
   blue). The mixing, the WCAG contrast and `readable` are `Rgba` methods with
   tests. The window's background is bg-app; the backdrop and bg-rail stay in
   `VoelinTheme` (gpui-component has no rail, and GPUI's gradient has two
   stops against Slint's three: the swatch draws the first and the last and
   says so).
The mode (`Choice`: system, light, dark) follows the window's appearance in
`system` (`observe_window_appearance` calls `set_system_appearance`; a light
or dark choice ignores the window) and sets the platform's window appearance
where the platform draws the frame (macOS; a no-op elsewhere). The text size
factor rewrites the metrics, the theme's font size (font-body) and radii.

theme/slint_parity.rs reads ui/theme.slint at test time (`include_str!`) and
compares every declaration of the `Theme` global with tokens.rs by name: the
colours (dark and light), every length with the file's own arithmetic (a
small evaluator of `*`, `+`, `max()` and token references) at four text
sizes, the weights, durations, the font family and the backdrop's stops, and
fails on a name on one side only or a declaration kind it does not know. A
mutation check (accent, radius-md and the top bar's formula changed in
tokens.rs) failed the tests with the names of the tokens, then was reverted.

fonts.rs adds the five Inter TTFs of the Slint front end (`include_bytes!`)
to GPUI's text system; the theme names the family. build.rs turns the 147
Lucide 1.48 SVGs of crates/voelin-ui/ui/assets/icons into a sorted table of
`include_bytes!` (std only, no new dependency) that assets.rs serves as
gpui-component's `icons/<name>.svg` before gpui-kit-assets' Lucide 1.43
catalogue (1,830 paths, which answers the rest and, as it does, an error for
a path it lacks); a test checks that `mic.svg` is the client's, differs from
the catalogue's, and that other icons fall through.

Development switches (dev.rs): `VOELIN_OPEN=swatch`, `VOELIN_DEV_THEME=
dark|light|system`, `VOELIN_FONT_SCALE`, `VOELIN_WINDOW_SIZE` (the Slint
front end's names where they exist). swatch.rs is the page: the 43 colours in
the groups of docs/ui.md's "Theme tokens" table with name and value (a test
checks each token is in exactly one group), the backdrop, radii, spacing,
the type scale, buttons, switches and checkboxes of gpui-component and 16
icons; it scrolls when the window is smaller. scripts/gpui-shot.sh makes the
screenshot headless the way scripts/shots.sh does for Slint (xvfb-run, or
GPUI_SHOT_HEADLESS=1 under headless.sh on NixOS; Wayland, the session bus
and the XDG directories out of the environment), then closes the window with
Alt+F4 and reports how the app ended. docs/ui/gpui-swatch-dark.png and
-light.png are its output (Xvfb :97, openbox, lavapipe via wgpu's Vulkan
backend, the debug binary, 1440x960, truecolour: a 256-colour reduction would
change the tokens' values; the Slint pictures live in docs/screenshots/, the
task asked for docs/ui/).

Checked on Rust 1.95.0: fmt, clippy -D warnings --no-deps (all targets, the
build script included), `cargo test -p voelin-gpui` 26 tests, cargo deny,
`scripts/notices.sh --check`.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 07:07:10 +03:00
faumarayandClaude Sonnet 5.5 27a13fcc7c voelin-gpui: the root Entity<AppState>, the engine's events through a foreground task, the one-second tick, later()
crates/voelin-gpui/src/app.rs holds the root entity: the toolkit-free
voelin_ui_vm state (`AppState<Vec<ChatLine>>`) and `Social`, with
`events::handle` as the one dispatch of an engine event (the entry point
both front ends use; its Update's engine commands are sent, its warnings
logged, the rest belongs to the slices that draw it). Three loops, spawned by
`AppState::new` and ended when the entity is released:
- the engine's events: a foreground task awaits the tokio receiver of the
  hosted engine (no reactor needed, as the plan says), `this.update` and
  `cx.notify()`: spike 3's hotkey task;
- the tick: a loop of `background_executor().timer(1 s)`;
- `Later`, for other threads: GPUI's `AsyncApp` holds an Rc-based weak
  handle and is not Send (read in gpui-pre's async_context.rs), so a thread
  that wants to touch the entity holds a Send handle that queues a boxed
  closure; a third foreground task, which owns the cloned AsyncApp, runs it
  with the entity. This is the Slint front end's `later(|app| ...)`.
engine.rs repeats the ~25 lines of voelin-ui's `HostedEngine::start` (the
engine on a tokio runtime, its events forwarded into an unbounded channel):
that type lives in the Slint crate (crates/voelin-ui/src/app.rs), which this
crate cannot depend on and this task does not touch. dev.rs reads
VOELIN_WINDOW_SIZE. lib.rs `run()` logs through tracing (`VOELIN_LOG`, else
`RUST_LOG`, else a filter that shows GPUI's adapter line), starts the engine's
runtime, opens the window on the entity and, on close, tells the engine to
close the sessions and ends the app. view.rs shows the one line of state the
task asked for: version, voice connections up, engine events handled, seconds
up; each part moves by one of the loops.

Seven tests, none needing a display (GPUI's test platform): an injected
engine event (a voice state) reaches the entity and its status line, the
entity notifies its observers, the tick runs once per advanced second, a job
from another thread runs on the entity, and a real engine (HostedEngine on a
tokio runtime) delivers a real event (a setting changed by a command) to the
entity through the same task; the window-size switch parses and refuses
nonsense. The real-engine test calls `allow_parking`, as GPUI's test
scheduler calls a wake from a tokio thread a non-deterministic test
otherwise. The tests use `gpui-pre` (renamed `gpui`) with its `test-support`
as a dev-dependency, pinned `=0.3.10` beside gpui-kit's own pin: gpui-kit's
`test-support` feature names the optional `gpui-fast` backend in weak
features, which makes cargo lock gpui-fast and its tree and pins taffy to
0.15.0 for every build (reproduced in a scratch project: 793 packages
without the feature, 820 with it). The lock gains only gpui-pre's own
test-support crates (proptest and its few, futures-concurrency, postage);
THIRD_PARTY_NOTICES.md does not move (dev-dependencies are out of it) and
cargo deny passes.

Run on Xvfb :97 (headless.sh) with the debug binary: the window opens in
0.1 s, shows "Voelin 0.0.1-alpha · 0 connections · 1 engine event · 2 s up"
and, four seconds later, "... · 6 s up" (the one engine event is the real
engine's own at start); Alt+F4 ends the app with exit code 0 in 132 ms.
Checked on Rust 1.95.0: fmt and clippy -D warnings (all targets, --no-deps),
`cargo test -p voelin-gpui` (3 runs, 7 tests each), cargo deny.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:56:08 +03:00
faumarayandClaude Sonnet 5.5 8f234e0051 voelin-gpui: the GPUI front end's crate on gpui-kit 0.8.1, a window titled Voelin that opens and closes
The second front end of plan section 6 step 3: crates/voelin-gpui with
the binary voelin-gpui, in the workspace's members and default-members next
to voelin-ui (two binaries until parity; voelin-ui stays the app).
gpui-kit is a workspace dependency pinned `=0.8.1` (the version the three
spikes were rebuilt on in the commit before). The crate asks for gpui-kit
and the app's name and id from voelin-platform (APP_NAME as the window's
title, APP_ID as its app id); `run()` opens one window whose
`on_window_should_close` ends the app, and returns the error when the
window cannot be opened (no display).

Checked on Xvfb :97 (headless.sh: openbox, a private bus, lavapipe through
wgpu's Vulkan backend, state under .scratch): the debug binary opens a
window named "Voelin" (xdotool search) in 0.3 s and ends with exit code 0
when openbox sends the close request (Alt+F4).

Cargo.lock: 279 more package entries (208 new names; no existing version
moved, other versions of 61 names were added beside theirs): GPUI's
gpui-pre family, wgpu 30, gpui-component with its Markdown, HTML, chart and
table support, cosmic-text, the Linux platform crates. The root workspace
already carried Slint's and the codecs' dependencies, so this is 195 new
packages on Linux, not the ~1,000 of the spikes' lock (which has the root's
packages too). deny.toml and about.toml name the two licences no crate of
the tree had: 0BSD (enum-iterator and enum-iterator-derive, under
gpui-component) and CC0-1.0 (notify 8, the file watcher of gpui-component,
and tiny-keccak, under the X input method client of gpui-pre-linux); no
other licence, no advisory, no ban and no source is new (`cargo deny
--locked --workspace check`: advisories, bans, licenses and sources ok).
THIRD_PARTY_NOTICES.md is regenerated (scripts/notices.sh, cargo-about
0.9.2, no warning; `--check` clean). There is no new clarification: cargo-about
finds every text.

Docs: CHANGELOG, docs/ui.md (the structure tree names the crate and the
intro the second front end), docs/building.md (the dependency list: Vulkan
or OpenGL at run time, what GPUI loads by name, a window manager on X11; no
new development package), README (the crate list and the run command) and
CLAUDE.md, which had no crate sentence (it only says "own crates"): it now
says there are two front ends on one engine and what they share.

Checked on Rust 1.95.0: cargo fmt and cargo clippy -D warnings --no-deps
over the own crates (all targets); cargo deny; scripts/notices.sh --check.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:46:59 +03:00
faumarayandClaude Sonnet 5.5 6fc84e9e44 spikes/gpui: rebuilt on gpui-kit 0.8.1 (gpui-pre 0.3.10, wgpu 30), nothing regresses; the pin result in the report
0.8.1 came out on 2026-10-26, a day after the 0.8.0 the three spikes were
measured on. `=0.8.1` in spikes/gpui/Cargo.toml and `cargo update -p
gpui-kit --precise 0.8.1` move 40 packages of the lock (1,069 entries
before, 1,065 after): gpui-kit, gpui-base, gpui-component and
gpui-kit-assets to 0.8.1, the 19 gpui-pre crates to 0.3.10, wgpu 29 to 30
(naga 29 to 30), taffy 0.13 to 0.15. No source change: the spikes build as
they were, release, on Rust 1.95.0.

One run of each README's measurement command on Xvfb :96 (openbox, a
private bus, lavapipe through wgpu's Vulkan backend, state under .scratch)
with the machine at a load average of 64 to 80 (the 0.8.0 runs: 28 to 53):
- composer drive.sh 8 PASS, ime.sh 3 PASS, windows drive.sh 11 PASS, no FAIL;
  the composer's screenshot differs from the committed one in 579 of 900,000
  pixels;
- video: static 1440p 22.7 fps shown at 259 % CPU (11.4 % of CPU per fps,
  0.8.0: 11.7), raw 1440p60 13.4 fps at 174 % (13.0; 0.8.0: 12.5 to 13.1),
  memory flat with drop_image, +408 MiB in 10 s without it; windows-both
  123 % of a core, the preview shown 14.4 of 15 a second, memory flat.
The frame rates are lower than 0.8.0's because of the load; the cost of a
shown frame is the same. The report says plainly that the 42 to 49 fps raw
1440p figures were not reproduced on 0.8.1, only the cost per frame was.

So the pin is gpui-kit 0.8.1, exactly. docs/design/gpui-spikes.md ("The
version to pin", the status paragraph, the setup table) and the spikes'
README say so; its figures stay 0.8.0's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:36:31 +03:00
faumarayandClaude Sonnet 5.5 e325b65d42 ashpd on async-io in voelin-media (pipewire) and voelin-platform (portal)
GPUI's Linux backend enables ashpd's `async-io` feature, and ashpd 0.13.13
refuses `async-io` and `tokio` at once (compile_error! in its lib.rs), so
a binary could not hold the portals and gpui-kit. voelin-media's `pipewire`
feature (the screen-cast and camera portals) and voelin-platform's `portal`
feature (global shortcuts, file chooser, proxy resolver) now ask ashpd for
`async-io`; Cargo.lock loses ashpd's edge to tokio and nothing else (the
package set is the same: THIRD_PARTY_NOTICES.md is unchanged and
`scripts/notices.sh --check` clean).

What zbus 5.19 does with the features (read in its abstractions/mod.rs):
with both `async-io` and `tokio` compiled in it picks per connection, tokio
when a tokio runtime is current on the calling thread, else async-io with an
I/O thread of its own. The workspace has both on already (notify-rust asks
for zbus/tokio, secret-service and others for its defaults), so the engine's
portal calls, which run inside its tokio runtime, still use tokio; a caller
with no runtime (GPUI's foreground executor) gets the I/O thread. Built on
its own, voelin-media has `async-io` only.

The source needed no change beyond a doc comment (capture/portal.rs said
the connection needs a tokio runtime). tests/proxy.rs gains a second test on
the same stand-in portal: ashpd's ProxyResolver called from a thread with no
tokio runtime, polled by hand, gets the answer. Both tests run again under
`dbus-run-session` on a bus of their own (the harness takes the test's name).

Checked on Rust 1.95.0: fmt and clippy (-D warnings, --no-deps) of the own
crates; `cargo test -p voelin-platform -p voelin-media`: all pass, including
tests/proxy.rs (2 tests), the portal-less-bus tests of both crates run with
no session bus (`unavailable_without_session_bus`, the `proxy::tests` that
need none), and tests/pipewire_apps.rs against a private PipeWire and
WirePlumber (found on PATH, ran: 2 passed in 2.7 s). The live portal
(a desktop's screen-cast dialog, the shortcut binding) was not exercised:
no desktop session is used by these runs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:18:00 +03:00
faumarayandClaude Sonnet 5.5 5ce5c0db82 Rust 1.95: rust-toolchain.toml, the workspace rust-version and the gateway image; the lints 1.95 adds
gpui-kit (every gpui-pre 0.3.x) calls std::hint::cold_path, stable since
1.95.0, so the client moves from 1.94 to 1.95 before the GPUI front end
can build (docs/design/gpui-spikes.md, "Rust 1.95 or newer"). rustc 1.95.0
(59807616e 2026-04-14), cargo 1.95.0, clippy and rustfmt of the same
release were used.

rust-toolchain.toml and the workspace's rust-version say 1.95;
crates/voelin-gateway/Dockerfile builds from rust:1.95-bookworm (cargo
refuses a 1.94 image once rust-version is 1.95). docs/building.md names
the Rust version for a local build; docs/ci.md says a channel change in
rust-toolchain.toml is all the runner needs (they named no version
before).

Clippy of 1.95 adds `collapsible_match` for an `if` that is a match arm's
only statement, `unnecessary_sort_by` and `manual_checked_ops`; they
flagged seven spots in four crates, none a behaviour change:
- voelin-media capture::forward: a let-else instead of a match whose arm
  holds one `if`;
- voelin-media ffmpeg::sys: `sort_by_key` with `Reverse` (two places);
- voelin-media studio:📷 `checked_div` for the frame interval;
- voelin-stream peer and session: the condition in a local before the
  `if` (a guard would carry a side effect: `remove`);
- voelinctl engine and session: the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 06:00:40 +03:00
faumarayandClaude Fable 5.1 296664ffa9 Merge phase5/gpui-spikes: the three GPUI spikes (video frames in img(), the composer with preedit, a second window on the shared model) and docs/design/gpui-spikes.md: go for all three
CI / Linux checks (push) Failing after 0s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 05:04:06 +03:00
faumarayandClaude Fable 5.1 df3b2074b9 spikes/gpui: voelin-model pinned at c5bb6b9 like the client's crates (one voelin_model in the graph after the keystore merge)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 05:04:06 +03:00
faumaray 02b2b470fc Merge remote-tracking branch 'origin/main' into phase5/gpui-spikes 2026-10-27 04:59:04 +03:00
faumarayandClaude Fable 5.1 ee971f30bc docs/design/gpui-spikes.md: the matched --no-drop re-run claims no cause for its rate (review minor)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 04:59:04 +03:00
faumarayandClaude Sonnet 5.5 8c172f4dc5 spikes/gpui/README.md: the nightly clippy command; report: 9.6 as measured
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 04:54:24 +03:00
faumarayandClaude Sonnet 5.5 6f2c64aa63 docs/design/gpui-spikes.md: video headline labelled raw, quiet-window pipeline figure, the --no-drop XDamage row explained
The headline video figure (status table, the go paragraph, the software
bullet) is the raw source, frames from memory with no decoder: it now
says so. The pipeline rows (22.9 fps at 1080p, 9.6 at 1440p) were load
artifacts: the page now carries the reviewer's quiet-window run of
pipeline-1440p60 (40.8 fps shown, XDamage 41.3, encoded 50.4, decoded
49.5, process 1047 %, encoder 454 %, llvmpipe 476 %, memory flat, load
23.5 / 30.6; not repeated here, the load stayed above 40), says the
pipeline rows scale with free CPU (the in-process encoder takes 450 to
1000 %) and that the cases are bound by CPU contention, the encoder being
the largest user. The go verdict stays.

The XDamage exception of the --no-drop case is a measurement artifact,
not frames counted and not presented: measure.sh runs damage-count for
69 s with 10 s of warm-up while the case lasts 12 s with 2 s, so the mean
spreads two seconds of window over 59. Second by second the counts match
(13.8 against 13.6; the reviewer's run 5.2 against 5.1) and a re-run with
the counter set to the case's own length gave 6.8 against 7.0 (Xvfb :93,
lavapipe, load 43 / 47). The video README's case row says so. No code
change.

The status paragraph records this round in two sentences (gpui-kit 0.8.1
of 2026-10-26 still unmeasured).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 04:51:49 +03:00
faumarayandClaude Sonnet 5.5 24069ac170 spikes/gpui: clippy -D warnings clean on nightly (as_chunks, bounded range)
Nightly's clippy flagged the two chunks_exact(4) loops of
common/src/bgra.rs (chunks_exact_to_as_chunks): both now use
as_chunks::<4>() and as_chunks_mut::<4>() (stable since 1.88). Behind
them, because clippy stops at the first crate that fails, it flags the
raw source's `for n in 0u64..` in video/src/main.rs
(for_unbounded_range): now `0..=u64::MAX`, the same loop.

`cargo clippy --locked --all-targets -- -D warnings` is clean on 1.95.0
and on nightly 2026-10-24 (through shell.sh); the README and the
report's clippy sentence say so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 04:45:53 +03:00
faumarayandClaude Fable 5.1 439a47f656 Merge phase4/keystore-task34: the key store follows task 34 (a sign-out keeps every key, only a forget deletes), VoelinProtocol crates pinned at c5bb6b9, the load-proof checkpoint tests
CI / Linux checks (push) Failing after 0s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 04:42:24 +03:00
faumaray 9c4bd29cb2 Merge remote-tracking branch 'origin/main' into phase4/keystore-task34
# Conflicts:
#	CHANGELOG.md
2026-10-27 04:34:14 +03:00
faumarayandClaude Fable 5.1 997c07b70e docs: the 17.7 row says where the one-second bound went (review minor of the keystore minors round)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 04:34:02 +03:00
faumarayandClaude Opus 5.5 5c36aae55e docs: the spikes' nightly clippy result as it is
The report and the spikes' README said the spikes pass clippy on 1.95.0
and on nightly; the final run's nightly clippy (1.101.0-nightly of
2026-10-23) has a lint 1.95 does not, chunks_exact_to_as_chunks, which
flags two chunks_exact(4) loops in spikes/gpui/common/src/bgra.rs. Both
now say so; the code is left as it is (clippy on 1.95.0, the pinned
toolchain of the spikes, is clean at every commit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 03:24:09 +03:00
faumarayandClaude Opus 5.5 3167817b89 docs/design/gpui-spikes.md: the three GPUI spikes measured, go for all three
Plan section 6 step 1's report: the setup (Xvfb :91 with openbox, Mesa
lavapipe through wgpu's Vulkan backend, gpui-kit 0.8.0, Rust 1.95.0, the
load of each run), and per spike the figures and checks with a go/no-go
against the plan's criteria:

- video: img() with the port of video.rs' delivery holds 42 to 49 fps at
  1440p60 and 55 to 58 at 1080p60 on the software device, the static
  control 60 to 62; drop_image keeps the atlas flat (without it +1.9 GiB
  in 10 s); a new 1440p picture costs GPUI's thread 6 to 7 ms (a new atlas
  texture and two copies); a persistent texture needs a GPUI change; the
  Slint demo stream compared on the same display at its 720p30;
- composer, IME, chat lines: all checks pass, X11 preedit with fcitx5 and
  Pinyin works, Wayland preedit not exercised headless; colour emoji in
  U+1F600-U+1F640 need a one-line GPUI patch (tried in a scratch build);
  InteractiveText loses clicks shorter than a frame;
- second window: shared root entity, focus, fullscreen, close and the X11
  global hotkey all pass; the shared preview's cost.

Settled for step 3: gpui-kit =0.8.0 (0.8.1 noted), Rust 1.95 (the 1.94
error), ashpd on async-io, the wgpu renderer (not blade) on X11 and
Wayland, Inter and Lucide, the theme tokens against gpui-component's, the
first slice, the plan's risks restated, the open choices, and what this
attempt changed in the interrupted one's work.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 03:18:23 +03:00
faumarayandClaude Opus 5.5 b6f8f16108 spikes/gpui: headless-wayland.sh stops its compositor
nixpkgs' sway wrapper runs sway under a dbus-run-session of its own when
no session bus is set, so the script's kill reached dbus-run-session and
every run left a headless sway behind. It now runs sway-unwrapped, which
is the process it kills, and clears sockets a dead compositor left in its
private runtime directory before it waits for the new one's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 03:12:16 +03:00
faumarayandClaude Opus 5.5 f9f95dbf0d spikes/gpui: the Slint app's logs stay out of the desktop's state directory
headless.sh and headless-wayland.sh set XDG_STATE_HOME to the run's state
directory as they set the other XDG directories: the Slint app (the
slint-720p30 case) keeps its log files there, and its runs had written
them to the desktop's ~/.local/state/voelin/logs.

measure.sh waits for the Slint app's window (up to 60 s; it took more than
20 s to appear on a busy machine, past the fixed 8 s the case waited) and
then measures it for the case's full length. The video README gives the
static cases and the Wayland run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 02:38:08 +03:00
faumarayandClaude Opus 5.5 1ffcf690cc spikes/gpui/windows: spike 3, a second window on the shared model
A main window and a Studio-like window (cx.open_window through
gpui_kit::open_window) both render views that observe one root entity: a
counter both change, the push-to-talk state, which window is active, and
the studio's preview. Closing the studio window docks it
(on_window_should_close), closing the main window ends the app, F11
toggles fullscreen, Ctrl+Tab activates the other window. The global
push-to-talk key is voelin-platform's X11 hotkey (XInput2 raw events),
read by a GPUI foreground task. The preview comes from voelin-media's
studio compositor and its preview tap, one BGRA RenderImage shown by both
windows, the replaced one dropped from every atlas. drive.sh runs the
scenario and its checks on the headless display.

From the interrupted attempt, changed here: the window's size after a
fullscreen toggle is logged once the window manager has set it (the
toggle's own bounds are the old ones) and checked (1000x900 back);
drive.sh says how long the app took to end; measure.sh (new) runs the
three cost cases into $OUT instead of the README's commands, which wrote
into the current directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:43 +03:00
faumarayandClaude Opus 5.5 c81d4ea666 spikes/gpui/composer: spike 2, the composer, preedit and chat lines
gpui-component's Textarea as the composer (auto-grow, placeholder), emoji
from a picker of voelin-ui-vm's emoji archive inserted at the caret,
pictures and file paths pasted as attachments (Textarea::on_paste),
Ctrl+Enter bound to Send in the Input context after gpui-component's own
bindings. Sample messages go through voelin_ui_vm::chat::line and are drawn
as StyledText with one GPUI text run per TextRun inside InteractiveText,
links clickable (masked ones ask first). The preedit is GPUI's own (XIM on
X11, text-input-v3 on Wayland); the spike reads the marked range and
prints it. drive.sh runs the scenario on the headless display, ime.sh the
X11 preedit with fcitx5 and Pinyin.

From the interrupted attempt, changed here: runs instead of highlights, so
each run has its font (emoji runs in Noto Color Emoji, code in the theme's
monospace font: the row's font_family("monospace") resolved to no
monospace font); a sample line of the smileys DejaVu Sans also has; the
picker in the emoji font; the font probe (whose get_font_for_id printed
"?" for every fallback font) replaced by an emoji probe that counts the
glyphs GPUI draws in colour (ShapedGlyph::is_emoji), printed by drive.sh as
findings for the system's and a Noto-only font configuration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:43 +03:00
faumarayandClaude Opus 5.5 fd421b9982 spikes/gpui/video: spike 1, decoded video as BGRA RenderImages in img()
video.rs' delivery (deliver, FrameSlot, Handoff, Buffers; video.rs:360-480)
ported to GPUI: the decoder hands over its newest frame only, a converter
thread turns it into an Arc<RenderImage> (BGRA, spike_common::bgra), the
window takes the newest from a Latest in render and drops the one it
replaces from every window's atlas (cx.drop_image). A RenderImage owns its
pixels with no way back to them, so Buffers' reuse cannot be ported.

Sources: --mode pipeline is LocalPreview with SourceId::Synthetic through
the real VP8 encoder and decoder, as Video::demo; --mode raw hands I420
frames from memory to the converter; --mode static (added in this attempt)
is the control: one picture, uploaded once, the window repainted every
frame. --convert rgba measures voelin-media's conversion in place,
--no-drop is the negative control for drop_image, --bench times RGBA
against BGRA. measure.sh runs every case on the headless display, with
damage-count beside it and the Slint app's demo stream for comparison.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:30 +03:00
faumarayandClaude Opus 5.5 c9859bcfb4 spikes/gpui: the GPUI spikes' workspace, environment and meter
Plan section 6 step 1. A Cargo workspace of its own under spikes/gpui (own
lock, not a member of the root workspace, so the root's lock, deny policy,
notices and CI are untouched; it builds into the checkout's target/), on
gpui-kit pinned to =0.8.0. No gpui-kit release builds on Rust 1.94 (every
gpui-pre 0.3.x calls std::hint::cold_path, stable since 1.95), so the
workspace says rust-version 1.95.

- shell.sh: the toolchain (1.95.0, 1.94, stable or nightly, all from one
  pinned fenix), the native libraries, Mesa's lavapipe as the only Vulkan
  driver, Xvfb, openbox and the X tools, Noto Color Emoji and Noto Sans CJK.
- headless.sh: a private Xvfb display with openbox and a private session
  bus, never the desktop's; headless-wayland.sh: sway's headless backend.
- spike-common: CPU by thread group and memory from /proc once a second
  with the spike's counters (meter), proc-meter and damage-count for
  programs without a meter (the Slint app), Inter and the emoji/CJK fonts,
  the client's Lucide icons as GPUI assets, and the BGRA twin of
  voelin_media::convert::to_rgba.

From the interrupted 2026-10-25 attempt, kept; changed here: shell.sh takes
1.94 and nightly from the pinned fenix (the store paths it named were
garbage-collected), the README's headless-wayland.sh paragraph (sway, not
weston), its fmt command (-p, not --all), its toolchain and nixpkgs lines,
and the font docs (GPUI drops Noto Color Emoji from a fallback chain).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:43:20 +03:00
faumarayandClaude Fable 5.1 2e985d793c Merge phase5/ui-vm-2: the remaining Slint controllers split into toolkit-free logic (voelin-ui-vm) and Slint bind files, the engine-event transitions in vm::events::apply, the ui-vm gate follow-ups (plan section 6 step 2)
CI / Linux checks (push) Successful in 25m39s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:59:44 +03:00
faumarayandClaude Sonnet 5.5 f183b22b63 voelin-store: the writer of the blocked-checkpoint test paces itself by its own commits
The first version of this test (2cbb816) still failed under heavy load, with
the sign-out itself returning DatabaseBusy. The cause is the writer's fixed
pause of 5 ms: when disk pressure makes each of its commits take 100 ms and
more, it holds the writer lock nearly all the time, and the sign-out, whose
busy timeout is the default five seconds, never gets it between two commits.
(The commit message of 2cbb816 blamed the writer's synchronous = FULL; the
setting is right to mirror the app, but it was not the cause.)

Reproduced without load by delaying every pwrite64 of the process by 700 ms
(strace -f -e inject=pwrite64:delay_enter=700ms): the test of 2cbb816 fails
with DatabaseBusy from the sign-out in two runs of two, this version passes in
two of two. The lib test of 2cbb816 passes with the same delay and with fsync
delayed by 3 s as well.

Now the writer pauses ten times as long as its last write took (5 ms at least),
so its share of the lock stays under a tenth whatever the disk does, and the
sign-out starts only after the writer has written once (a thread of a busy
machine can start after the whole sign-out is over, which made "the writer
never ran" a failure of the machine). A drop guard ends the writer if an
assertion of the test fails first.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 10:54:10 +03:00
faumarayandClaude Fable 5.1 4491ecee25 Merge main (3930ef2) into phase5/ui-vm-2
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:45:33 +03:00
faumarayandClaude Fable 5.1 785bbd050b docs: the three minors of the Opus gate of phase5/ui-vm-2
docs/ui.md: the app.rs row of the step-3 table points the toolbar and
tree refreshes at servers/bind.rs, where they live; app.rs only calls them.
voelin-ui-vm host.rs: the doc of Update::rest matches the events module
(the Studio's stream, a changed setting, the offline-message answers; the
watched and shared streams are state and go through the stream effects).
CHANGELOG: the two visible fixes of the branch are named instead of
"nothing changes on screen".

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 10:45:33 +03:00
faumarayandClaude Sonnet 5.5 8c891a057e docs: session-seam 17.6 records the double listing in the trait's sign_out
When the device key's own row carries a device-only binding, the provided
KeyStore::sign_out of VoelinProtocol (c5bb6b9) lists the key twice in
SignOut.unbound: in its loop over the identities bound to the account and in the
Auto branch. The tests of this repository use contains and do not mind (a probe
counted two entries for the key with either value of bound_existing_key); the
fix is a follow-up for VoelinProtocol.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:16:21 +03:00
faumarayandClaude Sonnet 5.5 2df0b91edd CHANGELOG: the key store entry in the present tense
"The key store now keeps the device key when signing out ...", with the
sentence that nothing changes on screen yet kept.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:15:43 +03:00
faumarayandClaude Sonnet 5.5 9f720d75bd docs: rewrap the four lines of the key store text that passed 80 columns
Two in docs/architecture.md (the sign-out paragraph and item 2 of open
question 10) and two in docs/session-seam.md 17.6 (the voelin-store leak
bullet), refilled to the width of the files. The words are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:15:31 +03:00
faumarayandClaude Sonnet 5.5 2cbb816686 voelin-store: the two blocked-checkpoint tests no longer decide by the clock
a_reader_that_blocks_the_checkpoint_... and store::tests::a_blocked_checkpoint_...
bounded the wall clock of a checkpoint (1 s) and gave the concurrent writer a
busy timeout of 1 s. A checkpoint ends in two fsyncs, which take seconds under
disk pressure: the review's sequences failed 7 of 8 and 6 of 8 at I/O pressure
of 10 to 30 %, and dd conv=fsync loops beside 32 busy loops made the lib test
wait 6 s and the sign-out 5 s ("database is locked" for the writer,
DatabaseBusy for the sign-out, whose writer neighbour committed with
synchronous = FULL).

The integration test now asserts what it means without a time: the sign-out
finishes, the writer (set up as the app's connections are, synchronous =
NORMAL, a busy timeout of a minute) gets through without an error, and one
checkpoint is made for the four removals. It is renamed from "costs
milliseconds". The lib test sets the connection's busy timeout to an hour, calls
checkpoint_truncate once and requires that it came back while the reader still
held its snapshot (the reader lets go from a watchdog after 30 s, so a
checkpoint that does not give up fails the test instead of hanging it), that the
reader blocked it, and that the timeout is the hour again. With the line that
sets CHECKPOINT_WAIT removed the lib test fails after 30 s.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 09:14:22 +03:00
faumarayandClaude Sonnet 5.5 9e9db0e160 docs: CHANGELOG for the key store and the leak, and the old protocol revision named nowhere
CHANGELOG: one line under Changed for the sign-out that keeps the device key
and the identity text that errors no longer repeat.

docs/session-seam.md: the four places that named the old protocol revision (the
reading list of the design, slice 1, the conformance run, the lock merge of the
gate round) are records of that round; they now say "the pin of that round" and
name c5bb6b9 only where it is the revision the statement was checked at (the
suite has 17 cases in the same order at c5bb6b9 too).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:08:51 +03:00
faumarayandClaude Sonnet 5.5 18b280df7e voelin-store: a damaged TeamSpeak identity row is reported by its kind of damage, never by its text
Store::identity and Store::identities read the stored JSON of a TeamSpeak
identity with `?`, so a row whose data was damaged outside the client came back
as Error::Json carrying serde_json's message, and that message quotes a value
it refuses: tsproto reports a key that does not import as an invalid value, the
key string and all. The error reaches status lines, events and logs.

identity_from_json classifies the error as voelin-core's ts::identity::from_json
does (voelin-core depends on voelin-store, so the classification is here too):
Error::Identity { damage: IdentityDamage, line, column } says malformed, cut
short, not an identity or unreadable, and where, and nothing of the text.
Error::Json stays for the bookmarks and settings, which hold no secret.

The key store was checked as the recorded leak (docs/session-seam.md 17.6)
names it, and does not leak: check_teamspeak (keystore.rs) drops the parse
error with `let Ok(..) else`, Columns::level uses `map_or`, and the warning of a
damaged binding names the row's kind and uid. A test pins that too.

tests/identity_text.rs damages a row six ways (a key that does not import, a
counter of the wrong type, syntax, a text cut inside its key, bytes that are no
UTF-8 as a BLOB and as TEXT) through a second connection, calls everything of
Store and SqliteKeyStore that reads or writes it, and looks through the errors
(text, Debug and sources) and every log line at TRACE (a capturing subscriber in
tests/support) for any 8 characters in a row of the row's data. A control shows
that serde's own message quotes the value and that the capture sees a warning.
With identity_from_json returning the old error the first test fails, naming
the quoted key; the key store test is a guard.

docs/session-seam.md 17.6: the leak bullet is closed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:08:35 +03:00
faumarayandClaude Sonnet 5.5 412f909d18 docs: the key store keeps every key at sign-out; the three parts of open question 10 and the duties of the GPUI client (Phase 2 task 34)
docs/architecture.md, "Identities": the sign-out wording follows the trait of
c5bb6b9 (the device key stays, unbound, whether it predates the account or not;
the account record and the synced copies are what it deletes; the release is
the service's operation and the same local sign-out; the deletion of an account
releases every device key and the same sign-out is its local half), and records
the screens' duties as the GPUI client's: the sign-out dialog with "Forget this
device's identity" and an export first, the release in Settings -> Account, and
the delete-account dialog, which must warn that the account's servers become
unreachable and offer an export of the device keys first. The reasons of the
refusal of a synced device key and of the checkpoint are reworded to match
keystore.rs.

docs/session-seam.md 17.6: a bullet for the key store's follow-up, with what it
did and what it did not need (no release call, no "released" record).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:02:31 +03:00
faumarayandClaude Sonnet 5.5 ca142fd3f2 voelin-store: the local half of releasing a device key is the sign-out, and the store needs nothing more
AccountClient::release (voelin-account-client at c5bb6b9) asks the service to
release the key and then runs KeyStore::sign_out with DeviceKeyChoice::Auto, so
the unbind of one key that keeps its data is the sign-out's own step (and a put
of the blob without its binding for a single key). Open question 10 and
protocol 13.6 ask the client to remember nothing: the service holds the
registration of the key, and the client learns that a key is still registered
with an account it signed out of from the service's answer to a sign-in or a
sign-up (CONFLICT, field device). So there is no "released" record and no new
store call; keystore.rs says so, and says the same of the deletion of an
account, whose local half is this sign-out.

Two tests pin what the client relies on after a release: the key is kept byte
for byte and unbound, then is the device key of a record of another account,
and a sign-out of that account keeps it again (its copies go); and a release
whose local half was cut short is finished by a sign-out with Auto, and a
second one finds nothing to do.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 07:01:42 +03:00
faumarayandClaude Sonnet 5.5 c0e8a533a4 voelin-store: SqliteKeyStore follows task 34, a sign-out keeps every key and only a forget deletes one
The module documents of keystore.rs are rewritten to the rule of open question
10 (accounts design, answered 2026-10-24): a sign-out keeps the device key
unbound whether it predates the account or the client made it for the account
(bound_existing_key is the client's wording and no rule reads it), the
identities only this device holds are unbound and kept, and "Forget this
device's identity" is the only deletion of a key of the device: signed in it is
sign_out with DeviceKeyChoice::Forget(uid), signed out it is KeyStore::remove
(a TeamSpeak identity: Store::delete_identity). The store has no export call;
the docs say where the UI reads the bytes (voelin_key + to_pkcs8, Store::identity
+ ts::identity::export) before it forgets, which also serves the delete-account
dialog's export of the device keys.

What a sign-out still deletes is not a key of the device, and the docs now say
so truthfully: the synced copies of integration secrets (private keys, scrubbed
from the file and its log like any deleted key), the account record (no
secret), and with Forget the device key. That is why SignOutPass stays: the
trait's sign-out removes those rows, and the log is still truncated once after
the last step, not per row, and not at all when nothing was deleted.

The refusal of a synced device key stays and is reworded: the sign-out keeps the
device key, but its first step deletes every synced copy before it reads the
record, so a device key stored synced would be deleted all the same.

Tests (the turned-around ones are in the previous commit): the device key's
whole row is unchanged by a sign-out, with and without the flag; a key that
carries a device-only binding is unbound and nothing else of its row changes;
a sign-out scrubs what it deletes and leaves the kept keys in the file; the
blocked-checkpoint test counts exactly one blocked checkpoint for four
removals (Forget, so the removals are four as before), through a TRACE-level
capture in tests/support; a sign-out that deletes nothing does not checkpoint;
a key kept by a sign-out is exported, forgotten with no trace in the file or
the log, and restored from the export.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 06:58:22 +03:00
faumarayandClaude Sonnet 5.5 4bd3d7a971 deps: voelin-identity, voelin-proto and voelin-model at VoelinProtocol c5bb6b9 (Phase 2 task 34)
The three protocol crates move together, as docs/building.md says: the
identity crate depends on voelin-proto of the same revision, so moving it
alone would put two voelin-proto packages in the lock.

c5bb6b9 is the protocol's main with task 34 (open question 10): the provided
KeyStore::sign_out keeps the device key whatever AccountRecord.bound_existing_key
says (only DeviceKeyChoice::Forget deletes it), and the crate gains Adoption,
Release and REVOCATION_KIND_RELEASED. Nothing in the workspace needed a source
change to compile (cargo check --workspace --all-targets --locked is clean on
1.94); the conformance Fixture of voelin-proto now holds an Arc<dyn Backend>,
and FakeHandle implements it, so the two callers build as they were. The
suite still has 17 cases, in the same order, so the two comments that named
the old revision name c5bb6b9.

Cargo.lock: the three source lines only. `cargo update -p ...` also flips
windows-sys 0.52 to 0.61 and itertools 0.14 to 0.13 in unrelated entries;
those are not taken, `--locked` accepts the file without them.
THIRD_PARTY_NOTICES.md regenerated (scripts/notices.sh): unchanged, the
workspace and git crates are not in it.

The voelin-store tests that pinned the old sign-out (a key made for the
account is deleted by Auto) are turned around here, in the same commit,
because they cannot pass with the new trait: the key stays, unbound, and only
Forget deletes it. The rest of the sign-out follow-up (the module documents,
the refusal wording, the new tests) is the next commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 06:53:29 +03:00
faumarayandClaude Fable 5.1 3930ef2945 Merge phase5/test-hygiene: test hygiene after the runner-image round (DatabaseBusy twin, closed-port race, the load-only flakes, ts6_banners alone with its server, docs/testing/load.md)
CI / Linux checks (push) Failing after 5m13s
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 06:12:04 +03:00
faumarayandClaude Fable 5.1 8614b120fe docs: load.md records the review's undecodable_video flake and the seven unformatted intermediate commits
The review's 100 whole-binary runs of the head saw
media::tests::undecodable_video_is_noticed_through_the_pipeline fail once
at load 106-146 (untouched by the round); it joins "Seen and left alone".
cargo fmt differed at seven intermediate commits, not six (the shell-only
5c029a9 sits on the unformatted tree); the orchestrator waives per-commit
rustfmt for them, fixed forward in 94195db, history not rewritten.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 06:11:47 +03:00
faumarayandClaude Sonnet 5.5 f791d3926f docs: testing/load.md names its own commits
The record's table said "this one" for the commit that adds the page; there
are two, the page and its record.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:54:19 +03:00
faumarayandClaude Sonnet 5.5 376925a96e docs: testing/load.md records the round, its commits and what ran
The record of the round at the top of the page, in the form of the earlier
rounds' records: the branch and its base, the fallback for the unregistered
mao-* agents, the commit table (which commits are the cut-off run's, which are
this attempt's, which are beyond the list), the two hunks dropped from the
cut-off run's tree, and a table of the checks that ran on the final tree. The
scope test's row gets the failures of the earlier tree that only had the first
half of its fix.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:54:03 +03:00
faumarayandClaude Sonnet 5.5 d4ccb8c8b8 docs: testing/load.md, how to make a machine busy and what the load-only tests assert
The recipe of the round (32 busy loops beside many runs of a test binary, a
build before and one after run alternately), the rules the fixes followed, the
table of the tests that failed only under load with their counts before and
after, the account-change test of the seam follow-ups (not reproduced; the
timing of its steps against its deadlines, and the reading of the code that
found no race), the tests seen at heavier load and left alone, and the
engine stage of the live smoke (ts6_banners failed because the test shared the
TeamSpeak 6 server with the others; what the smoke still does not do
reliably). docs/ci.md points to it from the section on the job image.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:34:05 +03:00
faumarayandClaude Sonnet 5.5 ad806606ac Say in the smoke script which of its checks still flake
After the roundtrip and ts6_banners fixes the smoke passed two of three runs
on the head of the branch; the third failed at the directory check of the
TeamSpeak 6 stage, `the directory did not list the stream`. The viewer of that
check ends when it has 30 frames and the script looks for the directory's
`"title"` line, which the viewer prints only if its own gateway session had
connected by then; in the failed run it was still `observe=Connecting`. The
fix is in voelinctl engine (end the viewer on both), not in a round about
tests, so the comment above directory_check records it, with the earlier
`expected output did not appear` of the gateway stage that was seen with the
same engine state.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 04:34:05 +03:00
faumarayandClaude Sonnet 5.5 f508e5bec4 Count frames, not a pause, in the automatic-bitrate test's "not per frame" check
Beyond the list of this round, found by its final whole-binary run: 1 of 150
runs of the voelin-core lib beside 32 busy loops failed in
an_automatic_bitrate_follows_the_stream, at the assertion that the sink is told
the layer's format once per change and not per frame (`left: 2, right: 1`), and
the unchanged test failed 2 of 900 runs of its own beside the same load.

The sink is told twice for the first picture, and the test counted in between:
Streamer::attach tells it the format from the size captured so far (when a
frame has been captured before the attach), and the encoder tells it again
before its first frame, because its record of what it told starts empty. The
test waited for the format, took the count, slept 200 ms and compared; on a
busy machine the encoder's first frame comes later than the 200 ms.

The test now waits until a frame has been handed over (the encoder tells before
it hands over, so both tellings are done), takes the count, waits for five more
frames, and compares: "per frame" is counted in frames. The deadline of 30 s
only ends a hang. 0 failures of 600 runs of the test beside 32 busy loops.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:59:07 +03:00
faumarayandClaude Sonnet 5.5 94195db16a Format four spots of the test changes of this round with rustfmt
cargo fmt on the own crates changed these four places of the commits before:
the match arm of ask_files_until, the closure of the features test, the count
closure of streamer_sends_opus and the call of preview_until in the studio
test. No change of meaning. Each of those commits passes clippy on its own;
rustfmt was not clean in them until this one.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:42:19 +03:00
faumarayandClaude Sonnet 5.5 5c029a982a Start the smoke's action when its listener is on the server, not after 3 s
roundtrip started the listener in the background, waited a fixed 3 s and ran
the action (the poke, the private message, the avatar request, the file
upload). A dev server that is slow to let a client in (4 s and more, 13 s
seen, when the machine is busy) left the action running against a client that
was not on the server yet: `error: message: the client is not on the server`,
and `FAIL: private message: the action failed` (the action's client printed
`connected: 2 clients` and the listener's `connected: 1 clients` came after).
That is one of the places at which the earlier steps of the smoke flaked.

voelinctl engine prints `connected: N clients` once its client is on the
server and has seen the presence, for every action; roundtrip now waits for
that line in the listener's log (60 s at most, and not when the listener has
ended) and then 1 s more, for the others on the server to see the listener.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:30:02 +03:00
faumarayandClaude Sonnet 5.5 069fd2ac12 Run ts6_banners with the TeamSpeak 6 server to itself
The engine stage of the live smoke failed in every run that reached it, before
and after every recent branch, at crates/voelin-core/tests/live.rs
`disabled policy must prevent HTTP requests` (ts6_banners, left: 4, right: 0),
while the six tests of the file passed one after the other.

ts6_banners sets and unsets the TeamSpeak 6 server's banners, and it counts the
requests that reach an HTTP server of its own for the images it set, to show
that an engine whose policy is disabled makes none. The server tells every
client that connects while the banners are set where they are, and an engine
fetches what it is told (as it should): the other tests of the binary, which
cargo runs side by side, connect engines to the same server, and their
requests were counted as the engine under test's. Reproduced against the
development servers with the tests in pairs: ts6_banners alone passes (62 s),
with ts6_avatars, ts6_engine or ts6_channel_joins at the same time it fails
(`left: 2` or, in the join test's case, a later count, `left: 6, right: 4`),
and the TS3 and TS6 tests without it pass in any combination. So the test was
wrong, not the engine or the script's ordering: it needs the server to itself.

The TeamSpeak 6 tests that connect now hold a lock shared and ts6_banners
holds it exclusively, so it runs before or after them and not meanwhile. The
smoke is not run with --test-threads=1 for this: that would hide it, not
remove it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:29:42 +03:00
faumarayandClaude Sonnet 5.5 661a607a35 Make two more link and media tests independent of how long the machine takes
Beyond the list of this round, found by its load runs and rarer than the tests
of the list: in about 500 runs of the whole voelin-core lib beside 32 busy
loops, a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks failed 3 times
(the scope had 1 channel, not 5,003) and streamer_sends_opus 2 times (the
`video too` expectation). The fixes are of the mechanism the code shows; the
runs after them (docs/testing/load.md) are too few to count a rate that low.

a_scope_...: the connector waits 250 ms for a link's first snapshot after it
said it is connected, and the test made its 5,000 channels after saying it, so
a busy machine made the session without them. The channels are made first. The
scope is also sent whole only if the presence is in the host's state when it
is asked for, so the test now sends a voice packet of one of the presence's
clients and waits for it to come through: the link takes its events in order,
and a packet of a client comes through only once the presence is in.

streamer_sends_opus: it waited for ten frames of audio and then expected a
frame of video, but audio is made quickly and a busy machine can keep the
video encoder from its first frame for longer. It now waits for ten frames of
audio and one of video, whichever the encoders make first; its deadline, 30 s,
only ends a hang.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:27:19 +03:00
faumarayandClaude Sonnet 5.5 92d02b0e00 Wait for the studio's delivered count in the capture-backend test
Beyond the list of this round, found by its load runs: in 150 runs of the
whole voelin-media test binary beside 32 busy loops, 11 failed, 9 of them in
packets_reach_the_outputs_and_the_studio_is_a_capture_backend at
`assert!(studio.shared.delivered.load(..) > 0)` (the other 2 in
it_composes_into_the_preview_and_follows_commands, fixed in the commit before).

The studio counts a frame as delivered after it has handed it to the capture
sink (`sink.frame(..)`, then `delivered.fetch_add`), so a test that has just
received the frame can read the count before it is made. The test now waits
for the count to become non-zero after it has the frame; the wait for the
frame is 30 s instead of 5 s, and the wait for the count 30 s, which only end
a hang.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:56 +03:00
faumarayandClaude Sonnet 5.5 9d04e0158a Wait for a preview frame of the size and scene asked for in the studio test
it_composes_into_the_preview_and_follows_commands took the first preview frame
after SetPreview and asserted its size. The studio composes from the moment it
starts, at the preview size and rate it has then (480x270, 15 fps), so the
first frame there is can be one of that size, composed before the command was
applied; on a busy machine it is. The 2 s waits for the new scene's colour
and the test's overall 5 s and 10 s limits measured the machine too.

preview_until now reads the preview until a frame that the test takes comes,
and looks at 20 frames at most: the preview keeps only the latest frame, so
few older ones are waiting or on their way, and the number of frames looked at
is the bound by the work. The wait for each frame, 30 s, only ends a hang.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:33 +03:00
faumarayandClaude Sonnet 5.5 77304604fe Let the stream task say when it is done in the layer-format test
layer_formats_reach_the_live_stream sent the same layer format a second time
and then slept 200 ms before asserting that no keyframe was asked for, which
tests that the stream task had not got to the command within 200 ms. It is the
task that asks for a keyframe (when the layer's bitrate changes) and it takes
its commands in the order they are sent, from the sink and from the handle
through the same channel. The test now sends a command whose answer is an
error event (Kick of a viewer, 65535, that is none) and waits for that
event: it comes after everything the format set going, and nothing is left to
wait out. A keyframe request the viewer's side makes late is not covered, and
none was seen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:33 +03:00
faumarayandClaude Sonnet 5.5 c5bb74ffcb Ask the file list one question at a time in the server-features test
the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list asked for
the lobby's file list every 20 ms until the answer was the one it wanted. The
bus holds 16 events, so on a busy machine the answers fell behind it (and
behind the host's work) and the one that counted was lost in the backlog, or
an answer to a question asked before the host narrowed what it offers was
taken for one asked after.

A helper, ask_files_until, now asks one question and reads the bus until that
question's answer comes, then asks the next only if the answer was not the one
wanted. Every question is answered before the next is asked, so those asked
after the update is pushed are the ones the update can refuse; nothing has to
be told apart by number, and nothing is waited out by the clock. The test
checks that the answer after the server lifted its list came from the host.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:33 +03:00
faumarayandClaude Sonnet 5.5 81c40a4b09 Wait for the states audio_sources_change_live asserts, and keep feeding the microphone
audio_sources_change_live failed 6 of 200 runs beside 32 busy loops, in two
ways. It waited for the sources' meters and then asserted their state and the
mixer's level and limiter, which are set at other times than the meters: the
state could still be Starting when the meters showed the tones. And its
microphone thread published 50 chunks of 20 ms, one second, and the source
takes what is published only from when it runs, which a busy machine delays
by any time, so the test then waited 5 s for a level that had gone by.

The first wait now includes the state, the mix and the limiter. The thread
publishes until the test has heard the tone (or, as a cap that ends a thread
whose test failed first, 120 s), and the second wait includes the window
source's error and the muted tone's own level, which the test asserted right
after it. The deadlines of the waits, 30 s, only end a hang; what is waited
for is a state.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:22 +03:00
faumarayandClaude Sonnet 5.5 25be4337a8 State what the preview's rates are, not what a busy machine reaches
The end of local_preview_decodes_the_pattern asked the rates of the second
since the first stats call to be 20 to 40 pictures and 100,000 to 5,000,000
bits a second. How many pictures a second the pipeline manages is a property
of the machine's load, and a second of sleep is longer than a second when the
machine is busy; neither is what the stats are about. What they promise is
that fps and bitrate are the counters' change over the time since the call
before.

The test now times its two stats calls and the sleep between them. The time
the stats measured lies between the two spans that the test measured around
it (from the end of the first call to the start of the second, and from the
start of the first to the end of the second), so the reported fps has to be
the pictures counted in that time, within the rounding of fps, and the
bitrate the bits counted in it, within the cut-off of bitrate. At least one
picture has to have come in the second.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:22 +03:00
faumarayandClaude Sonnet 5.5 f9bfd5d305 Check the test pattern's structure, not its pixels within a tolerance
rectangle_span, the pixel check of local_preview_decodes_the_pattern and
test_pattern_through_stream_tasks, asked every pixel further than two columns
from the rectangle's edges to be within 24 per channel of the rectangle's
colour or of the background. The streamer's VP8 speed control lowers the
quality when the encoder falls behind, and a flat colour then moves by 30 and
more per channel (seen: [33, 31, 101] and [50, 33, 48] for the background
[24, 40, 72], [255, 85, 5] for the rectangle [240, 90, 30]), still nowhere
near the other colour. A tolerance of 40 was tried and reverted: it only moves
the load at which it fails.

A pixel is now whichever of the pattern's two colours it is nearer to, and
what the test is about is the row's structure: background, one run of the
rectangle, background. The first and last pixel that are the rectangle's give
the span; everything between them, but the two blurred columns at each end,
has to be the rectangle's too, and the callers still check the span's width
and that it moves. A stray rectangle-coloured pixel in the background
stretches the span over background and fails there.

Before, the two tests failed 4 and 2 of 100 runs each beside 32 busy loops; see
docs/testing/load.md for the runs after.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:13 +03:00
faumarayandClaude Sonnet 5.5 0bc6abadfe Name the step in which the account-change test timed out
account_change_cancels_pending_handshake was seen to fail about once in 130
runs of the whole suite under load, and the failure was not kept. Its three
timeouts (5 s for the first handshake packet, 5 s for a packet from a new
socket after the account changed, 2 s for the connection to end after the
account source closed) were bare unwrap()s, so a failure said only that a
timeout had elapsed, at a line. Each now says which step it was.

No race was found, in the test or in the code it drives. The account receiver
has seen its version before the connection is made, so a change after the
first packet always restarts the connection; the restart opens a new socket,
so a packet from another port is a packet of the new connection; dropping the
sender makes changed() fail, which ends the loop with the reason the test
expects. The ways the test can fail are those three deadlines. With the steps
timed (a throw-away instrumented build, not committed), 300 runs of the test
alone, eight at a time beside 32 busy loops, all passed, and the steps took at
most 34 ms, 33 ms and 9 ms against deadlines of 5000, 5000 and 2000 ms. So
the failure needs a stall of seconds, which is the machine's and not a
property of the test; docs/testing/load.md has the numbers and what to do if
it is seen again.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 03:26:12 +03:00
faumarayandClaude Fable 5.1 de89fddcb6 deps: crypto-bigint 0.7.7, ctutils 0.4.5, rustls-webpki 0.103.16, tokio 1.54.1, webpki-root-certs 1.0.11 (RUSTSEC-2026-0382, -0383, -0385, -0386, -0387); notices regenerated
CI / Linux checks (push) Successful in 37m31s
RUSTSEC-2026-0387 stays on the crypto-bigint 0.5 and 0.6 lines that the
tsclientlib fork pins (p256 0.13 in tsproto-types, crypto-bigint in tsproto);
ignored until 2026-12-20 with the fork's move to p256 0.14 as the follow-up.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 02:44:31 +03:00
faumarayandClaude Sonnet 5.5 e465a55b9e Give the fallback gateway test a port that stays refused
the_next_published_gateway_is_used_when_one_fails took its "port nothing
listens on" by binding a listener to port 0 and dropping it at once. A port
that is free only for a moment can be given to another socket before the
engine connects to it: the other tests of the binary bind port 0 for their
fake gateways and proxies, and the one that gets the port answers the
connection, so the test then passes over a gateway that is no longer closed,
or fails on the 650 ms deadline.

The test now binds a TCP socket and keeps it, without listening, for its
whole length: the port is taken, so nobody else gets it, and a connection to
it is refused at once. It checks that refusal before it relies on it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:21:55 +03:00
faumarayandClaude Sonnet 5.5 ac957a0c87 Reopen the history database of the gateway test after the engine has closed it
history_on_open_paging_and_offline_messages drops its engine and opens the same
database again for the restart it tests, the same shape as the contacts test
that 0d67dd7 fixed: dropping an Engine does not close the history database, the
engine task ends later and closing the connection checkpoints the write-ahead
log under an exclusive lock, and a History::open meanwhile waits for that lock
only for the 5 s busy timeout, failing with DatabaseBusy on a loaded disk.

The test now waits until the -wal file is gone before it reopens. The helper
that does so (closed) moves from voice_features.rs to tests/common/mod.rs,
which both test binaries declare.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:21:55 +03:00
faumarayandClaude Sonnet 5.5 35408a3dfe Require the portal proxy test's child to report one passed test
The test runs itself again under dbus-run-session and, on a zero exit, returned
without looking at what the child printed. A child that ran no test at all
(its --exact filter matching nothing, as after a rename of the test) also exits
0 and printed "running 0 tests ... 0 passed", so the wrapper passed having
checked nothing. A zero exit now has to come with libtest's "test result: ok.
1 passed;" in the child's output, else the wrapper fails with that output.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:20:03 +03:00
faumarayandClaude Sonnet 5.5 7e63092bcd Say in from_json's doc who reads the identity text through it
The doc said every reader of the TeamSpeak identity text refuses it through
from_json. Only voelin-core reads it through there: voelin-store parses the
same text on its own (keystore.rs check_teamspeak and level, store.rs list),
and drops or forwards serde's message by its own rules. The doc now names
voelin-core and says voelin-store parses it too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 02:19:48 +03:00
faumarayandClaude Fable 5.1 2ffe5ffb99 Merge phase5/tests-under-runner: the workspace suite green as root inside the runner image
CI / Linux checks (push) Failing after 35m27s
Every machine assumption of the tests fixed (root writes anywhere, no sound
card, no session bus, no GPU, no FFmpeg, no H.264 encoder, no display beyond
xvfb, no TeamSpeak servers, no DNS); a cancelled download's part file removed
after its task stopped (a real defect a test exposed). docs/ci.md: how to run
the suite the way CI runs it. Sonnet review accepted; its three docs minors
are in the last commit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 02:04:09 +03:00
faumarayandClaude Fable 5.1 e807df40e5 docs: ci.md quotes the right git error, removes root's files, names the bare clone, follows main's loopback and D-Bus tests; .scratch/ ignored
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-25 02:04:08 +03:00
faumaray a8dbc5ba74 Merge remote-tracking branch 'origin/main' into phase5/tests-under-runner 2026-10-25 02:03:16 +03:00
faumarayandClaude Sonnet 5.5 6c8d4bbb61 Bring the status of docs/ui.md up to date with the merge of main 6e0df51
One paragraph: what the merge brought (the session seam, the CI deploy key, the
media codec test and the seam follow-ups, none of it in the UI crates), that the
.set_ counts of the table were counted again on the merged tree and stand, and
where the colour of a chat's avatar is chosen (servers::logic::conversation_tint,
pinned by a test).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:37:10 +03:00
faumarayandClaude Sonnet 5.5 08a899cf01 Pin the colour of a chat's avatar with a test that fails when it falls back to black
The ui-vm gate's minor "server_tint falls back to black" was closed by a
fallback in App::conversation_item, `.unwrap_or_else(|| vm::avatar::tint(&title))`,
that no test could fail: replacing it with `.unwrap_or_default()` (opaque
black) left cargo test -p voelin-ui -p voelin-ui-vm green.

The choice of (kind, session) -> colour is now a pure function in
voelin-ui-vm, servers::logic::conversation_tint(state, kind, session, title),
and messages.rs calls it. A test pins the three cases: a server chat of a
server in the list takes the rail's colour, a server chat whose server is
gone takes the colour of its title, and a channel's or a person's chat (with
or without a known server) takes the colour of its title. The titles are
chosen so that the title's colour differs from the server's, and the test
asserts that. App::server_tint, whose only caller this was, is removed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:36:19 +03:00
faumarayandClaude Sonnet 5.5 9e7452ec2a Merge main (6e0df51) into phase5/ui-vm-2
Main gained phase0/ci-private-dependency (the CI deploy key and the checks
action), phase5/media-codec-test (a media test stated for machines without an
H.264 encoder) and phase4/seam-followups (five flaky tests fixed, the
identity-text leak closed, docs/session-seam.md 17.8 onwards). None of it
touches the UI crates: the merge is clean, with no conflict, and Cargo.lock
and THIRD_PARTY_NOTICES.md are unchanged by it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:17:40 +03:00
faumarayandClaude Sonnet 5.5 1de2725f19 Remove a cancelled download's part file after its task has stopped
The download test, which 61458df of this branch made wait for the part file,
exposed a defect of the link: a download reports Started just before it opens its part file, and the
open ran on tokio's blocking pool. Link::cancel() aborted the task and removed
the part file at once; when the cancel came between Started and the end of the
open, there was no file yet to remove, the abort cannot stop an open that is
already on the blocking pool, and the open then made an empty `<name>.part`
next to the target after the transfer had been reported Cancelled. The user
sees a leftover file, and a later download with `resume` continues from it.

files::receive now makes the directory and opens the part file with std::fs in
one step (the same kind of small blocking call as Sink::offset and the removal
in cancel, which already ran on the loop), so an abort, which takes effect at
an await, cannot come in the middle of it. Link::cancel() keeps the task's
JoinHandle instead of its AbortHandle, aborts the task, and removes the part
file and reports Cancelled from a task of its own after the aborted one has
stopped: the file the task made is then there to be found, or the task never
got to make one. Cancelled is therefore reported after the removal and after
the task has stopped, where it was reported before both.

The test goes back to the shape it had before 61458df: it cancels as soon as
the transfer is Started (and now fails loudly if it never was). That shape
failed in 10 of 100 runs of the voelin-core lib tests three at a time with 16
busy loops beside them on a 32-core machine, and in the final runs of the CI
test step in the runner image of this task (the second of three); with this
change it failed in none of 200 such runs. The link and files tests pass.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 23:07:48 +03:00
faumarayandClaude Sonnet 5.5 443559aa79 Take the keyframe baseline of the layer-format test after the streamer has settled
stream::tests::layer_formats_reach_the_live_stream asserts that telling the
sink the same layer format twice asks for no second keyframe: it drains the
sink's keyframe requests, changes the format, waits for the request that
follows, tells the same format again and expects none within 200 ms. It failed
once ("nothing changed", stream.rs:1326) in the first of the three final runs of
the CI test step in the runner image of this task, with the machine busy with
another job.

Requests reach the sink from the stream going live, from the streamer's own
view of its viewer connecting (PeerEvent::Connected, a moment after the viewer
sees WatchState::Connected, which is all the test waited for), from the
viewer's picture requests, and from a changed layer. The test drained once,
right after the viewer's side was connected, so a request of one of the first
three that arrives later is taken for the one the changed format asked for, and
the real one then arrives after the "same again" and is counted as a change.
This could not be reproduced here (0 in 400 runs of the single test, 32 at a
time with 48 busy loops, nor in 200 runs of the lib tests); the change closes
those windows as far as they can be named: the test waits for the streamer's
own Connected (StreamViewers) as well, and drains until a moment longer than
the merge interval of requests (250 ms) passes with no request, before the
format is changed. The assertions are those of before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 21:42:15 +03:00
faumarayandClaude Sonnet 5.5 272de7a13d Read the streamer's stats until they show what the viewer already saw
Two voelin-core tests read Streamer::stats() once, at the moment a consumer had
seen the effect, and the stats lag behind it:

- stream::tests::test_pattern_through_stream_tasks asserted `video_frames >= 15`
  right after the viewer had decoded 15 pictures. The encoder counts a frame
  after the sink has taken it (`sink.send_video(..)`, then `fetch_add`), so the
  15th picture can be at the viewer first: video_frames was 14 with
  captured_frames 15 and the picture on screen.
- media::tests::an_automatic_bitrate_follows_the_stream asserted the layer's
  bitrate in the stats right after the sink had been told the layer's format;
  the stats had 0 (the layer's target is stored by the encoder thread, not by
  the call that tells the sink).

Both now poll for the value with a deadline (5 s, and 10 s as the test's other
waits), which is the same assertion without the order of two threads. Before,
on a 32-core machine with 32 busy loops beside the runs: the first failed on
that assertion in 7 of 150 runs of the stream tests six at a time, the second
in 19 of 120 runs of the voelin-core lib tests six at a time. After, in 200
runs of the lib tests three at a time with 16 busy loops beside them, neither
failed on these assertions.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 21:42:03 +03:00
faumarayandClaude Sonnet 5.5 61458df625 Cancel the download test's transfer only once its part file is made
link::tests::a_file_is_downloaded_through_the_connection_the_link_opens waited
for the Started state and then cancelled, expecting the part file to be gone
100 ms later. The download reports Started just before it opens the part file
(files::download, then receive), and the open runs on tokio's blocking pool. A
cancel that arrives in between finds no part file to remove (link cancel()
removes it at once and reports Cancelled), the aborted task cannot stop the
open that is already going on, and the part file is made after the cancel:
`assert!(!part.exists())` failed. It did so in the second of the final runs of
the CI test step in the runner image of this task, and in 10 of 100 runs of
the voelin-core lib tests with three of them at a time and 16 busy loops
beside them on a 32-core machine (none in 200 such runs with this change).

The test now waits for the part file itself, which is what "the transfer
waits in the middle" means, and checks that Started was reported.

This is a real, if small, defect of the product that the test exposed: a
cancel in the moment between Started and the end of the open leaves an empty
`<name>.part` next to the target. It is not fixed here: closing it takes
reporting Started after the open (it also feeds the chat and the preview size
limit) or waiting for the aborted task before the part is removed, which is a
change of the transfer code and not of a test. Recorded in the report of this
branch.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 21:41:37 +03:00
faumarayandClaude Sonnet 5.5 637ee58979 Record log lines in the tests through one subscriber for the whole process
web::tests::info_lines read the lines a closure logs with
tracing::subscriber::with_default. While that scoped subscriber is the only
one alive, tracing-core registers a callsite that another thread meets first
against that thread's own default, which is none, and the callsite stays
disabled for every thread. session::banner_tests::
a_failing_banner_is_logged_once_with_its_address flakes this way (lines == []):
it failed in one of eight runs of the CI test step in the runner image of
this task (assertion `left == right` failed: [] left: 0 right: 1 at
session.rs:2541; it passed in the other seven). Several other tests reach the same
"banner not downloaded" callsite through image_finished while it runs.

info_lines now installs a recording subscriber as the global default the first
time it is called, and each call records into a buffer of its own thread, so
every callsite is registered against the same subscriber and no scoped
dispatcher is created or dropped while tests run. The result is the same: the
lines `f` logged at info and above on its thread. The new test
info_lines_see_a_callsite_another_thread_met_first fails with the old helper
(lines == []) and passes with the new one.

The same change is 4be37e1 on phase4/seam-followups (not merged yet; it
measured 1 failure in 300 runs of banner_tests before and 0 in 600 after),
taken here unchanged so that a CI run of this branch does not stop on it and
the two branches merge without a conflict.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 20:08:50 +03:00
faumarayandClaude Sonnet 5.5 26ee8c38c1 Document the fields of the mirrored bridge structs and lift the exemption
The gate minor "field docs on the mirrored bridge structs" was answered with
`#![allow(missing_docs)]` on `bridge` and `studio_bridge`, and the crate's
comment said 400 or so fields. The two modules have 559 pub fields; 210
carried a comment of the .slint files and 349 (288 and 61) had none there.
Each of those is described now, from the code that fills it (the producers
in the view model and in voelin-ui, the settings keys' own documentation,
the gateway protocol's types), and the allow is gone: `#![warn(missing_docs)]`
holds for the whole crate and clippy -D warnings fails on a field without a
comment (checked by deleting one). docs/ui.md and lib.rs give the real
numbers.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:56:38 +03:00
faumarayandClaude Sonnet 5.5 9aea876437 Ask improve_level for more than the test identity already has
ts::identity::tests::improve_level_keeps_the_key made its identity with
Identity::create(), which stops at the first counter whose level is 8 or more,
and asked improve_level for 13. About one identity in 32 has 13 or more
already, and improve_level then returns it as it is, so the assertion that the
counter grew fails. The test does not depend on the machine: it failed 9 times
in 300 runs of the single test on a developer machine, and once in the
offline run in the runner image of this task, a CI run that fails one time in
about thirty for it.

The target is now three levels above what the identity has, so the search
always runs. The assertions on the level, the callbacks and the counter use
that target.

The same change is 9254e08 on phase4/seam-followups (which also fixes four
other tests that fail on their own and is not merged yet): it is taken here
unchanged so that a CI run of this branch does not stop on it, and the two
branches merge without a conflict.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:53:00 +03:00
faumarayandClaude Sonnet 5.5 370eaf94ed Point the references to the controllers the split removed at their folders
`servers.rs`, `chat.rs`, `streams.rs` and `settings_page.rs` of voelin-ui
are `servers/`, `chat/`, `streams/` and `settings_page/` since the split
(the Slint side in `bind.rs`, the decisions in voelin-ui-vm), and
`adopt_server_name` is in the view model's `events`. The comments of
`events.rs`, `app.rs`, `studio/bind.rs` and `dev/bind.rs`, and the
add-server section of docs/ui.md, named the old files. The "before" names in
the table of the `.set_` counts stay: they are the files as they were.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:44:14 +03:00
faumarayandClaude Sonnet 5.5 b439b9fbb2 Count the status line's calls in docs/ui.md as the files have them
Of the 230 `.set_` lines of the seven files at ad20979, 36 are calls of
`set_status(`, not 37: the 37th hit was `set_status_text`, the Bridge write
inside `set_status`, which is one of the ten direct writes already. Say so,
and give the share of Bridge writes (186 of 230) next to the two fractions.
`messages.rs` has 11 `.set_` calls since the offline message's text is taken
in by the view model (the row said 12).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:43:51 +03:00
faumarayandClaude Sonnet 5.5 f8447ec9f8 Test that a picture of pixels reaches Slint as wide, as high and in place
The length check of the pixels is in `Pixels::new`, but the Rgba arm of
`convert::image` had no test: a picture drawn with its width and height
swapped passed all 22 tests of voelin-ui. A 3 by 2 picture whose pixels
hold their own column and row is converted, and its Slint size and four of
its pixels are read back (the swap fails the test).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:43:20 +03:00
faumarayandClaude Sonnet 5.5 56ce2cb739 Pin the notice kind names and the settings page title again
The social split deleted `notice_names_and_setting_pages` from voelin-ui
without moving it. The Slint side picks the bell's colours and icons by the
kind names ("poke", "mention", "event", "friend") and nothing but the one
"mention" assertion and the Keybinds search pinned them. The names of all
five kinds are tested next to `NoticeKind`, and the "Voice & Video" title
next to the list it is in.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:39:49 +03:00
faumarayandClaude Sonnet 5.5 91d70702f3 Take the text of an offline message in before the redraw, not after it
The social split left the offline message's state change in the front end's
`rest` events, which `perform` handled after it drew the conversations:
`refresh_chats` drew the open message while `dm.mail` was still empty and
the inbox row was still unread, and nothing drew the page again. Before the
split `social_event` wrote both ahead of `social_refresh`.

`Event::OfflineMessage` is now taken in by `social::logic::event` like the
other offline events: the text is `Social::mail`, the inbox row turns read,
and a failure is the status line. `events::apply` no longer parks the event
in `rest`, so a tape test in `voelin-ui-vm` sees it (the mutation that
parks it fails the test). `perform` also handles what is left in `rest`
(a setting, the studio's stream, the request answers) before it draws, as
every such event ran before the redraw ahead of the split.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:33:29 +03:00
faumarayandClaude Sonnet 5.5 172bee5337 Say what the tests print when they skip only as precisely as the code does
The table of docs/ci.md quoted one skip message per row, but the tests print
several wordings per piece (for the H.264 encoder: "skipped: no H.264
encoder", "skipped: needs VP8 and H.264 encoders", "no h264_vaapi or H.264
decoder, skipped"; for FFmpeg: "FFmpeg not installed, skipped", "no FFmpeg with
libavformat, skipped", ...), and some live tests return without printing. The
rows now say a skipped line naming the piece, and keep an exact string only
where the code has exactly that one.

The row on DNS and the internet sat under a column headed "The image has no",
which read as if the job had no network; it has, for apt, rustup and crates.
The column is now headed "A test cannot count on" and the row says the tests
use no DNS or internet and names the #[ignore]d ones that would.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:11:42 +03:00
faumarayandClaude Sonnet 5.5 ac6937289d Name in docs/ci.md the job image the runner really registers
Runner setup told to register ubuntu-24.04:docker://ghcr.io/catthehacker/
ubuntu:act-24.04 while the new section on the tests says the test step runs in
docker.gitea.com/runner-images:ubuntu-24.04. The runner of this machine
(gitea-runner-performance, register script of its NixOS unit) is registered
with ubuntu-24.04:docker://docker.gitea.com/runner-images:ubuntu-24.04, and
`docker ps` shows its CI tasks running that image, so the label line was the
stale one. It now names that image, the network list names its registry in
place of GHCR, and the tests section says it is the image of the
ubuntu-24.04 label.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:11:03 +03:00
faumarayandClaude Sonnet 5.5 cd08498092 Make the documented image run start cargo, and its VoelinProtocol mirror work
The docker run that docs/ci.md prints for the tests under the job image hung
for ever once the apt and rustup setup was done: bash -c execs its last
command, so xvfb-run became the container's process 1 and never started cargo
(probed: with the runner image and xvfb installed, xvfb-run -a as process 1
stays up with an idle Xvfb, and the same command under --init finishes). The
command now has --init. The runner is not affected: it starts its steps with
docker exec.

The hint for the private dependency is part of the block now, so the block
runs as printed: the bare clone is mounted at /protocol.git (it was never
mounted into the container before) and `git config` runs with -C /, because a
git worktree's .git file points outside the /src mount and git config in /src
exits 128 with "gitfile does not point to a valid repository".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 19:11:03 +03:00
faumarayandClaude Fable 5.1 6e0df5178e Merge phase4/seam-followups: the gate's identity-text minor, the H9 edge list, five flaky tests
CI / Linux checks (push) Failing after 27m35s
An unreadable TeamSpeak identity is refused without its key in the text (the
classification of from_blob shared as from_json); VoiceOptions fields and
Backends::set_account documented; docs/session-seam.md 17.6 holds the complete
engine/ts edge list for the second half; improve_level, the contacts database
reopen, the banner log subscriber, the two localhost tests and the portal proxy
test made deterministic. Sonnet review accepted; its five minors (two more
DatabaseBusy/port races in tests/gateway.rs, a 1-in-130 voice handshake flake,
the from_json doc, the proxy wrapper's success check) go to the next
test-hygiene round.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 17:32:58 +03:00
faumarayandClaude Sonnet 5.5 8541d7c9e5 Document what the Linux job image lacks and how the tests cope
The test step runs as root in docker.gitea.com/runner-images:ubuntu-24.04
with only the apt packages of the system-dependencies action. docs/ci.md now
says how to run the CI's test command in that image with --no-fail-fast, and
lists what the image has no (a regular user, sound card, PipeWire daemons, a
session bus, GPU and VA-API, FFmpeg, an H.264 encoder, Wayland, a browser, the
TeamSpeak dev servers) with what each kind of test does about it. It also
records that two voelin-core tests fail on a machine whose ::1 swallows
connections, whatever the change under test is.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 17:16:19 +03:00
faumarayandClaude Sonnet 5.5 2c9c739732 Make an_unwritable_path_fails_at_once hold for root
The test started a recording at /nonexistent-root-dir/x/clip.webm and expected
an error. Recorder::start creates the missing parent directories, which a
regular user cannot do below / but root can: under the runner image (Gitea
run 1091, docker.gitea.com/runner-images:ubuntu-24.04, root) the call
succeeded, created /nonexistent-root-dir and left a file behind.

The test now builds its unwritable paths in a temporary directory from things
that fail for every user: a path below a regular file (ENOTDIR, so
create_dir_all fails) and a path that names an existing directory (EISDIR, so
File::create fails). The unknown-container name is checked in the same place
and also asserts that no file was created. Reproduced in the runner image as
root with the old test failing and the new one passing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 16:42:41 +03:00
faumarayandClaude Fable 5.1 c91a3b719d Merge phase5/media-codec-test: peer_config_follows_codecs on a machine without an H.264 encoder
CI / Linux checks (push) Failing after 25m38s
The first CI run that could fetch the private dependency failed on this test
under the runner image. It now states preferred_codec's contract on any
machine. Reproduced and shown green inside docker.gitea.com/runner-images:ubuntu-24.04.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 15:34:27 +03:00
faumarayandClaude Sonnet 5.5 81def06144 Test that voice_options hands the version spec on as the spec
After the seam merge VoiceOptions::client_version is the spec string that the
engine resolves when it connects (docs/session-seam.md 17.3), and voice_options
only resolves it eagerly to tell the user at once. The test pins both: no spec
leaves None, a spec that resolves is passed on as written, one that does not
is refused with the message.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:29:30 +03:00
faumarayandClaude Sonnet 5.5 f374f5797b Record the round after the gate in the design of the session seam
17.8: the commits of the follow-up round, the five flaky tests (all fixed, how
each was reproduced and what the evidence is, including the two that are
rewrites and the one that was never seen again), and what ran on both
toolchains: fmt and clippy per commit, the lib suite ten times in a row on
each with no exclusions, the integration tests, cargo doc, the workspace check
with the environment that made it build, and the smoke script before and after
on fresh stacks. The status line names the round.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:26:46 +03:00
faumarayandClaude Sonnet 5.5 6329e56780 Make peer_config_follows_codecs state what preferred_codec promises on any machine
The test compared preferred_codec(&all, Some(H264)).is_some() with whether an
H.264 encoder exists. preferred_codec falls back to another encodable codec
when the configured one cannot be encoded, so is_some() is true on every
machine with any encoder and the assertion held only where an H.264 encoder
exists. The first CI run that could fetch the private dependency (Gitea run
1089, runner image without an H.264 encoder) failed on it; a developer machine
with FFmpeg or a GPU passed.

The test now says the contract: a configured H.264 is the result when
all.encoder_codecs() has it, and otherwise the result equals the automatic
choice, preferred_codec(&all, None). The built-in codecs (no OpenH264) pin both
branches on every machine: VP9 configured gives VP9, H.264 configured gives
the automatic choice, VP8.

The H.264-in-software offer assertion assumed VP8 second after H.264
(offer_codecs(&all, H264)[..2]). A hardware AV1 or VP9 encoder ranks before
libvpx's VP8, so a machine with software H.264 and one of them fails it (the
dev machine does with the named av1_vaapi encoder and hardware off). It now
says H.264 leads exactly the codecs the VP8-led offer has.

Checked at 9714dc2 in docker.gitea.com/runner-images:ubuntu-24.04 with the
apt packages of .github/actions/system-deps and rustup 1.94: the test failed
at media.rs:3426 and passes now; the voelin-core lib tests there were 268
passed, 1 failed, 2 ignored before and are 269 passed, 0 failed, 2 ignored
after.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:06:54 +03:00
faumarayandClaude Sonnet 5.5 d677273f06 Bring docs/ui.md up to date with the splits and what is left of step 2
The numbers of the .set_ table are counted with the command the text names, all
on one base (the files before this round's splits, ad20979) where the text
mixed the counts before and after the event move (chat.rs 38 or 33, servers.rs
37 or 32), and now include the social, dev and host files that the text left
out. Plan section 6 step 2 is stated as done, with what is left for the GPUI
step: the rest of app.rs, the small controllers, and the events page of
events.rs, which is no dispatch (the dispatch moved to voelin_ui_vm::events).
The two mirror modules' field docs are said to be exempted by the crate's lint
(349 fields), not documented. CHANGELOG.md's entry for voelin-ui-vm names the
areas that moved.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:01:01 +03:00
faumarayandClaude Sonnet 5.5 8aa5d6729b Write the user's gateway requests as a list, not an or-pattern
rustfmt 1.94 (the pinned toolchain) and the nightly rustfmt lay out the long
or-pattern of failure_text differently, so voelin-ui-vm, clean on both when it
was merged, was not any more. A list of the eleven requests is laid out the
same by both; the requests and the answer are the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 15:01:01 +03:00
Aleksey Selihov 9714dc2226 Merge pull request 'CI and release builds read the private VoelinProtocol repository' (#1) from phase0/ci-private-dependency into main
CI / Linux checks (push) Failing after 22m41s
2026-10-24 11:46:50 +00:00
faumarayandClaude Sonnet 5.5 c35bbb5ba8 Run the portal proxy test on a bus of its own, or say it checked nothing
voelin-platform's tests/proxy.rs says to run it under dbus-run-session, and
without DBUS_SESSION_BUS_ADDRESS it returned at once. With one set it ran on
the desktop's bus and failed at "the portal leaves the bus": the test has its
stand-in release org.freedesktop.portal.Desktop, and the first call afterwards
starts the real xdg-desktop-portal, which the bus can start by name; it
answers instead of the "missing" the test expects for a minute. A private bus
from plain dbus-run-session starts it the same way (the test failed the same
three times under it here), so the documented way did not work on a desktop
that has the portal installed.

The test now runs itself again under dbus-run-session with a bus configuration
of its own, a session bus without service directories, so that nothing on it
can be started by name. Without dbus-run-session, or when the bus does not
come up, it says "skipped, nothing was checked" with the reason and passes;
when the test ran on its bus and failed, it fails with the output. The
stand-in and the assertions are the ones that were there.

On the bus with the default services the same inner test still fails as
before (checked by hand), and on the bus of its own it passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:32:53 +03:00
faumarayandClaude Sonnet 5.5 a90bb70ee6 Let the test SOCKS proxy dial localhost at the IPv4 loopback
web::tests::pictures_go_through_the_proxy_named_for_each_hop downloads
http://localhost:<port>/banner through a SOCKS5h proxy of its own and asserts
that the proxy was given the name "localhost:<port>". The test proxy then
connected to that name through the system's resolver, and on a machine that
resolves localhost to ::1 only (this one) the server, which listens on
127.0.0.1, was not reachable: the download timed out after 20 s.

The proxy still reports the name it was given, as SOCKS5h says, and dials
localhost at 127.0.0.1 like the server it stands in front of.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:29:29 +03:00
faumarayandClaude Sonnet 5.5 e614a1c3f1 Probe localhost at the IPv4 loopback in the discovery test
discover::tests::without_records_the_gateway_itself_is_asked starts a server on
127.0.0.1 and has the discovery ask the gateway at "127.0.0.1",
"127.0.0.1:9987" and "localhost". The probe connected to the name through the
system's resolver, and on a machine that resolves localhost to ::1 only (this
one) nothing listens there: the third address found no gateway.

The test helper that makes the probe, probing, connects to localhost at
127.0.0.1 instead. What the test checks is that the gateway is asked at the
name localhost, not what the resolver makes of it, so it no longer depends on
the resolver.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:29:29 +03:00
faumarayandClaude Sonnet 5.5 4be37e1fd1 Record log lines in the tests through one subscriber for the whole process
web::tests::info_lines read the lines a closure logs with
tracing::subscriber::with_default. While that scoped subscriber is the only
one alive, tracing-core registers a callsite that another thread meets first
against that thread's own default, which is none, and the callsite stays
disabled for every thread. session::banner_tests::
a_failing_banner_is_logged_once_with_its_address flaked this way (lines == [],
once in a full run of slice 3); several other tests reach the same
"banner not downloaded" callsite through image_finished while it runs. The old
helper failed 1 of 300 runs of banner_tests, and always on a single thread
that meets the callsite first (the new test below).

info_lines now installs a recording subscriber as the global default the first
time it is called, and each call records into a buffer of its own thread, so
every callsite is registered against the same subscriber and no scoped
dispatcher is created or dropped while tests run. The result is the same: the
lines `f` logged at info and above on its thread. The new test
info_lines_see_a_callsite_another_thread_met_first fails with the old helper
(lines == []) and passes with the new one; the new helper failed 0 of 600
runs of the same tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:28:07 +03:00
faumarayandClaude Sonnet 5.5 0d67dd7433 Reopen the contacts database after the first engine has closed it
voice_features::contacts_are_kept_in_the_database dropped its engine and opened
the same database again at once. Dropping an Engine does not close the history
database: the engine task ends later, the history writer is joined there, and
closing the connection checkpoints the write-ahead log under an exclusive lock
with fsyncs. The second History::open waits for that lock only for the 5 s busy
timeout, and fails with DatabaseBusy when a loaded disk makes the close take
longer (seen as 3 failures in 8 runs, 10 in 24 with eight runs at a time).

The test now waits until the -wal file is gone, which SQLite does when the last
connection closes, before it reopens: the restart of a process, as the test
means it. With every fsync of the test process delayed by 6 s (strace -e
inject=fsync,fdatasync:delay_enter=6000000) the old test failed every time at
the reopen with DatabaseBusy, and the new one passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:24:30 +03:00
faumarayandClaude Sonnet 5.5 9254e08daa Ask improve_level for more than the test identity already has
ts::identity::tests::improve_level_keeps_the_key made its identity with
Identity::create(), which stops at the first counter whose level is 8 or more,
and asked improve_level for 13. About one identity in 32 has 13 or more
already, and improve_level then returns it as it is, so the assertion that the
counter grew failed: 8 failures in 300 runs of the single test before this
change, 0 in 300 after.

The target is now three levels above what the identity has, so the search
always runs. The assertions on the level, the callbacks and the counter use
that target.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:21:22 +03:00
faumarayandClaude Sonnet 5.5 96ff0e0028 Write down the complete edge list between the engine and src/ts for H9
17.6 of docs/session-seam.md named two engine-to-ts edges; the Opus gate of the
merge found the rest. Each line was checked with rg and cargo tree:

- the engine into src/ts: Backends::default and register_teamspeak, the uid and
  id rule of the projection, gateway.rs from_blob/to_blob (H5), the public
  voelin_core::ts paths and their users in voelinctl and the UI crates, the
  API docs that link into ts, and the test-only edges;
- what a TeamSpeak connector in another crate cannot do with
  Backends::register (no LocalCtx, no StreamPort): streams across the crate
  boundary need H2 or a public extension trait;
- src/ts into engine-private items (link, stream, files, offline, the crate
  root, settings), with the conclusion that the "by git tag" step needs H1 and
  H2 or a shared vocabulary crate, else voelin-core and voelin-gateway-ts form
  a cycle;
- what else keeps tsclientlib and tsproto in voelin-core's tree, so that the
  exit check needs H5 too, and voelin-store, voelin-stream and
  voelin-gateway-proto lose the dependency;
- the split of stream.rs;
- the same key-quoting leak in voelin-store's Store::identity, not closed.

The H9 row of 11.2 points to the list and no longer says the exit check holds
after H1-H3 alone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:20:02 +03:00
faumarayandClaude Sonnet 5.5 84f4a4835f Make cargo doc of voelin-ui-vm pass with -D warnings
RUSTDOCFLAGS=-D warnings failed with twelve errors, none of them new
behaviour: public docs linking to the private server_lines and PRESETS
(plain code spans now), Event::... links in state.rs that name voelin_core's
Event without importing it (voelin_core::Event::..), an unclosed <id> tag in
a bridge field comment (a code span), and three explicit link targets that
the label already resolves to.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:19:17 +03:00
faumarayandClaude Sonnet 5.5 371e4d77c8 Merge main (c60acf9, the session seam) into phase5/ui-vm-2
The engine of main runs on voelin_proto::link::Session; this branch had split
the Slint controllers into <area>/logic.rs (voelin-ui-vm) and <area>/bind.rs
(voelin-ui) before that merge and was never reviewed. One conflict, the one
the Opus gate of the seam merge predicted:

- crates/voelin-ui/src/servers.rs (modify/delete): this branch had split the
  file into servers/bind.rs and voelin-ui-vm's servers/logic.rs; main had
  changed the file for the seam (docs/session-seam.md 17.3). The file stays
  deleted and the changes of main are made where the code now is:
  servers/bind.rs sends ts::identity::to_blob(&identity) in ConnectVoice and in
  both ObserveGateway sends, builds voelin_core::QueryLogin {address,
  allowlisted: false} with voelin_core::QueryTransport for ObserveQuery, names
  ts::identity::DEFAULT_NICKNAME, and its tests import ts::identity::{Found,
  LaunchImport}; servers/logic.rs imports ts::identity::LaunchImport (and
  links ts::identity::import_new), and voice_options keeps the eager
  ts::versions::resolve for the message and assigns Some(spec.clone()) to
  VoiceOptions::client_version (the engine resolves the spec when it
  connects).

Cargo.lock merged without a conflict and differs from main's only by the edge
of voelin-ui-vm to roxmltree, which this branch added (d9de95b).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:18:43 +03:00
faumarayandClaude Sonnet 5.5 563482db72 Document VoiceOptions.nickname and server_password; correct Backends::set_account
Both fields were carried over from ConnectOptions without a doc: what the
nickname is on each kind of server and that an empty one falls back to the
link's nickname parameter; that the server password is Hello.password, falls
back to the link's password parameter and is not the channel's.

Backends::set_account said the connectors use the account (the QUIC
connector's certificate, the TeamSpeak connector's myTS ID proof). No connector
reads ConnectParams.account yet: the TeamSpeak one is given the myTeamSpeak
account through TsConnector's setters, and the QUIC connector does not exist.
The doc says so and names H4 as the step that moves the proof to this hook.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:17:16 +03:00
faumarayandClaude Sonnet 5.5 a856f90c6b Refuse an unreadable TeamSpeak identity without its key in the text
The Opus gate of the merge found that ts_session::inner_options put the raw
serde_json error into the refusal of an identity it cannot read, and tsproto's
key visitor reports a key that does not import as invalid_value(Unexpected::Str(
key), ..), so the private key string reached LinkEvent::Disconnected(Some(text)),
Event::Error and the UI status line.

The classification ts::identity::from_blob already had (malformed, cut short,
not an identity, unreadable, with line and column, never the value) is now
ts::identity::from_json, which takes the JSON text; from_blob and inner_options
both use it, so the refusal is worded in one place. A credential that is not
UTF-8 is refused as "it is not text".

Tests: identity::tests (a key that lost its last two characters: the JSON
reader's own message quotes it, from_json and from_blob do not; no 8-character
piece of the key), ts_session::tests (inner_options), link::tests (the
LinkEvent::Disconnected text through SessionLink with the real connector) and
session_fake (ConnectVoice through the engine: the Disconnected state, the
Error event and every event after it). All three connector-side tests fail with
the serde_json text put back.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 14:16:06 +03:00
faumarayandClaude Fable 5.1 c60acf9de0 Merge phase4/session-seam: the engine on voelin_proto::link::Session (plan Phase 4 step 7, first half)
CI / Linux checks (push) Failing after 49s
Slices 1 to 3 of docs/session-seam.md plus the merge of main ad20979 and the
minors round: SessionLink and the Backends registry put the engine on
Arc<dyn Session>; the TeamSpeak implementation is a Session under
voelin_core::ts; ServerLink, TsLink, LinkCmd, LinkEvent, LinkCtx and Remote are
private; VoiceOptions, QueryLogin and IdentityBlob are the public API changes.
Sonnet review accepted each slice; the Opus gate accepted the branch with one
minor (the TeamSpeak connector's refusal of an unreadable identity puts the
serde_json error, and so the key text, into the message: a follow-up).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 13:56:17 +03:00
faumarayandClaude Fable 5.1 37f8fe9bc1 Say what the transfer commands did before f1df886: a notice and a hanging report, not a dropped connection
The review of the merge-and-minors round read ts/voice.rs: the Input::Cmd arm
sends a command's error as LinkEvent::Error and keeps the connection, so the
old anyhow::bail! never ended the TeamSpeak session. The 17.7 row said it did.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 12:57:30 +03:00
faumarayandClaude Sonnet 5.5 d5d85b3f3d Record the round after the review of slice 3 in the design of the session seam
17.7: the merge of main (ad20979), what it conflicted on and what it needed to
compile, the four minors of the review with their commits, and what ran on the
merged tree: fmt and clippy per commit, tests on both toolchains, the lib
suite ten times in a row, cargo doc, the acceptance of section 10 (including
the rustdoc JSON walk), the notices check, and the smoke script and the live
binaries before and after. The status line follows.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 11:43:48 +03:00
faumarayandClaude Sonnet 5.5 f1df88690b Fail a transfer the TeamSpeak link is given, not its connection
ts::voice::Voice::command answered LinkCmd::Download, Upload and CancelTransfer
with anyhow::bail!, which ends the whole TeamSpeak connection: chat, voice,
presence and the stream task with it. SessionLink copies the bytes of a
transfer itself and never sends them, but a command that does arrive is that
transfer's failure, not the connection's. Download and Upload answer their
report with TransferState::Failed and the connection goes on; CancelTransfer
has no report and nothing to cancel, so it is logged at debug.

A unit test gives an unconnected Voice the three commands: each returns Ok, the
two reports see Failed, nothing is pending.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 11:00:57 +03:00
faumarayandClaude Sonnet 5.5 76a884a779 Correct the paths and statements slice 3 left stale
- docs/session-seam.md 4.1: the TsConnector owns the myTeamSpeak account since
  a451f02; it is not registered "with the engine's watches".
- docs/session-seam.md 16.1: the live tests are src/ts/ts_session/live_tests.rs.
- docs/session-seam.md section 10: the acceptance rg is given as it runs from
  the repository root (--glob '!**/ts/**'); from crates/voelin-core/src the
  first glob is '!ts/**'.
- ts/voice.rs module documentation: the type that runs it is ts_link::TsLink
  (crate::TsLink is gone).
- link/tests.rs: ts/ts_session/driver.rs.
- voelin-store (IdentityOrigin::Imported, a one-word path) and
  docs/research/ui-review.md: voelin_core::ts::identity, ts/voice.rs.
- docs/audio.md: LinkCmd::Audio and LinkEvent::Audio are in link/mod.rs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 11:00:17 +03:00
faumarayandClaude Sonnet 5.5 f0d20cc02f Document QueryLogin.transport
The one public field of QueryLogin without a doc comment.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 10:58:50 +03:00
faumarayandClaude Sonnet 5.5 87926e9b59 Refuse a TeamSpeak identity that holds no JSON
link::connect::credential sent a TeamSpeak IdentityBlob with an empty json as
an empty Credential::Foreign blob, which is what the TeamSpeak connector reads
as "make an identity up" (identity: None). An identity that holds nothing is no
identity: it is refused with SessionError::Protocol, as the Voelin branch
refuses a key that cannot be read, before any connector is asked. The comment
of ts::identity::to_blob ("a blob with no JSON is refused when it is used")
holds on both paths now: the gateway's from_blob already refused it.

Two tests: connect_params refuses "" and white space and still sends none as
the empty blob; an engine on the fake host answers ConnectVoice with the reason
and the connector is never asked and makes no session.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 10:58:34 +03:00
faumarayandClaude Sonnet 5.5 e13d401b9c Merge main (ad20979) into phase4/session-seam
Main brings the merge of phase5/ui-vm: the toolkit-free crates/voelin-ui-vm
crate and the logic/bind split of crates/voelin-ui. Conflicts, and what each
resolution keeps:

- crates/voelin-ui/src/settings_pages.rs: main deleted it (it is
  settings_pages/{mod,bind}.rs and voelin-ui-vm's settings_pages/logic.rs
  now), this branch had changed its voelin_core::identity paths. Deleted; the
  paths are voelin_core::ts::identity:: in bind.rs and in logic.rs.
- crates/voelin-ui/src/identities.rs: the module comment names
  voelin_core::ts::identity::import_new (this branch) and settings_pages/
  (main).
- docs/architecture.md: the voelin-core row of this branch with the
  voelin-ui-vm and voelin-ui rows of main.

Not conflicts, but needed to compile: voelin-ui-vm named the in-tree
voelin-model by path, which this branch moved to the protocol repository
(workspace dependency), and imported voelin_core::identity::Found, which is
voelin_core::ts::identity::Found. Cargo.lock merged without a conflict and
resolves with --locked; THIRD_PARTY_NOTICES.md is up to date
(scripts/notices.sh --check).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 10:32:05 +03:00
faumarayandClaude Sonnet 5.5 6a08147f93 Record slice 3 in the design of the session seam
Section 17: what was done, commit by commit; where the code differs from the
text of section 10 (QueryLogin.allowlisted, the ServerLink trait moved rather
than made private, Backends::register_teamspeak, files::upload deleted, the
directory the acceptance rg runs from); the API changes that phase5/ui-vm-2
has to absorb; the acceptance list; what ran against the baseline (fmt,
clippy per commit, tests on both toolchains, cargo doc, notices, the smoke
script and the live tests before and after); the follow-ups. The status line,
4.1, 4.8, 9, 11.2 (H9's two edges into src/ts) and 16.1 follow.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 08:28:14 +03:00
faumarayandClaude Sonnet 5.5 d0092e467a Describe the session seam in the architecture document
"The server link" is "The session seam": the registry, SessionLink and the
vocabulary it shares with session.rs (crate-private now), what a session asks
for in VoiceOptions, the TeamSpeak module (voelin_core::ts), StreamPort, the
tests, and what is still TeamSpeak-shaped. The crate table row of voelin-core
follows.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:27:49 +03:00
faumarayandClaude Sonnet 5.5 f63d459865 Keep the crate's documentation free of links that do not resolve
cargo doc with warnings denied failed on efacb41 and on main alike, with eight
errors (six with the media features on): the cache's module documentation
linked to private items, and the crate documentation to modules and a type
that exist only with the media features. They are plain code spans now, so
that RUSTDOCFLAGS='-D warnings' cargo doc --no-deps -p voelin-core passes,
with and without --features media-desktop.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:24:37 +03:00
faumarayandClaude Sonnet 5.5 ca34f84610 Let a query login say that its address is on the server's allowlist
The engine's own query connections used the query crate's default line
options, which keep a client-side limit of nine commands in three seconds. The
live tests passed voelin_query::Connect with that limit off, because the
development servers allowlist their clients, and with the limit on the
channel relay of ts3_engine and ts6_engine did not connect within the two
seconds the test waits before it speaks. QueryLogin gets the one bit the
tests had: allowlisted, off for the application (which cannot know), on for
the tests, and the UI's login says false, as it always effectively did.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:23:46 +03:00
faumarayandClaude Sonnet 5.5 d70a3582f2 Take the transfers the engine does itself out of the TeamSpeak connection
voice.rs handled Download, Upload and CancelTransfer with a copying task per
transfer, a progress cadence, the picture limits and a cancel table; none of
it is reachable since SessionLink copies the bytes itself over the
connections OpenRead and OpenWrite open (the picture limits and the
negotiation deadline live there, tested in link/tests.rs). The connection
keeps the two connection jobs and refuses the three commands in words;
files::upload and its close wait go with it (SessionLink uses upload_to, and
the TCP test of the upload runs through that), and the test of the picture
download time moves to the cache, which owns the function.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 07:07:52 +03:00
faumarayandClaude Sonnet 5.5 1edc52ce74 Make the engine's link vocabulary private and the options neutral
VoiceOptions is a struct of its own, no longer an alias of the TeamSpeak
link's options: identity is an IdentityBlob and client_version a spec for
ts::versions::resolve, which rides the address as the link parameter
client_version and which the TeamSpeak connector resolves (a spec it refuses
fails the connect in words). SessionLink builds the connect parameters
(link/connect.rs: the bookmark's link, the hello, the credential of the
identity's kind, now also a Voelin key's signer) and session.rs holds it
directly: the ServerLink trait between them was redundant. The trait lives
on in the TeamSpeak module (ts/ts_link.rs, with the TeamSpeak-typed
ConnectOptions) for TsLink and the in-memory link of the tests.

ServerLink, TsLink, LinkCtx, LinkCmd, LinkEvent and Remote are crate-private,
Engine::start_with_link is gone, and the three tests that needed the inner
link (tests/link_fake.rs) are unit tests of link/ now. The rg over the crate
for tsclientlib, tsproto and voelin_query, outside ts/ and the three files
that use them privately (gateway.rs, query.rs, stream.rs), is empty. The UI
and voelinctl get compile fixes: the identity blob and the spec string.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:59:44 +03:00
faumarayandClaude Sonnet 5.5 be84874a09 Take the gateway's identity as a blob and the query login as the engine's own type
Command::ObserveGateway.identity is a Box<IdentityBlob> (a TeamSpeak
identity as the key store keeps it; voelin_core::ts::identity::to_blob and
from_blob convert) and gateway::connect takes the blob too; gateway.rs reads
it itself, and one it cannot read ends the observation with its reason
instead of reaching the gateway. Command::ObserveQuery.connect is a
QueryLogin (transport, address, user, secret, server port and id) that
query.rs turns into voelin_query::Connect with the query crate's own line
options, which is what the UI always passed. voelin_core re-exports
IdentityBlob; voelin-identity is a dependency of voelin-core now, so
Cargo.lock gains that edge (the crate was in the graph already, and no
third-party package is added: THIRD_PARTY_NOTICES.md is unchanged).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:29:50 +03:00
faumarayandClaude Sonnet 5.5 a451f027f3 Give the myTeamSpeak account to the TeamSpeak connector, not to the engine
Command::SetMytsIdentity and SetMytsData are gone (nothing sent them): the
account's proof and what servers are shown of it belong to TeamSpeak, and the
engine only forwarded two watch channels through every session to the link's
context. TsConnector is public now, with set_myts_identity and set_myts_data;
it owns the senders (shared by its clones through its TsLink) and each
connection holds them for as long as it runs, so a session outlives its
connector as it outlived the engine's loop. Backends::register_teamspeak
takes a connector whose clone the application keeps, and Backends::default
registers one of its own. LinkCtx, LocalCtx, SessionHandle and Session lose
the watches, and the test of the standalone context's senders is a test of
the account's: a connection keeps it open.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:17:16 +03:00
faumarayandClaude Sonnet 5.5 029b8464b7 Move the TeamSpeak implementation into src/ts
ts_link.rs, voice.rs, book.rs, ts_session/, versions.rs and identity.rs move
under crates/voelin-core/src/ts (git mv, so git log --follow keeps their
history). voelin_core::versions and voelin_core::identity are
voelin_core::ts::versions and voelin_core::ts::identity now; the UI and
voelinctl follow with the new paths. Nothing else changes: the module
declarations, the use paths and the path of Versions.csv are the only
edits to the moved files.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 06:08:10 +03:00
faumarayandClaude Sonnet 5.5 362e2b9da1 Assert the unique ids and the server's uid in the presence test
presence_follows_the_host_until_it_ends showed the clients' names and
channels but not what the engine keys contacts and private history by: the
unique id of each client (the base32 of a Voelin user's 32 bytes) and the
server's unique id in ServerDetails.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 05:58:27 +03:00
faumarayandClaude Sonnet 5.5 b92379d01b Name the replaced session and the refused stream in tests of their own
The tail of a_reconnect_finds_the_state_the_first_session_left (a connect
while connected replaces the session) and the end of
commands_reach_the_host_as_requests (a host without streams is not asked
for one) are tests of their own now, so that each name says what is
checked.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 05:56:28 +03:00
faumarayandClaude Sonnet 5.5 dd9140e1ea Check that the conformance suite is known before the cases that do not apply run
cases_that_do_not_apply_fail zips the suite's cases with EXPECTED, so a case
the protocol repository adds would have been left out without a word. It
calls the_suite_is_known first, as the conformance subset does.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 05:55:52 +03:00
faumarayandClaude Sonnet 5.5 efacb41894 Correct the record of a reconnect's replay and of the live module's prerequisite
Section 16 of the design said that after a reconnect to a v1 host the
display is right and only the store is wrong, because Dedup drops the copy
of the event. That holds only for the messages within 4 s of the newest one
seen: Dedup evicts what is older than that relative to the incoming
message, so a replayed older message is shown again as a live Event::Chat
and stored again. Corrected in 4.4, 16.1, 16.4 and F3 (16.5), with the two
ignored tests that pin the display and the store, and in P17 and H10: only
the CHAT-cursor resume cures both, and only within an epoch.

Also: the introduction of section 16 names the two production changes (F1,
F2), not three; the move-back test now sends two messages 10 s apart and
the record says what the single-message version did not prove; the live
module raises the anti-flood limits itself and the record says so and what
ran (a fresh stack before and after, in series and in parallel, and the
smoke script before and after on freshly reset stacks); the toolchains of
the review round, the nightly that replaced 2026-10-19, and the per-commit
checks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 04:54:16 +03:00
faumarayandClaude Sonnet 5.5 9283191e58 Raise the anti-flood limits of the development servers from the live module
On a freshly started stack the live module failed 8 tests of 12 with
ConnectFailedBanned: a server with its default anti-flood limits bans the
address that connects as often as these tests do, after three or four
connections. scripts/it-smoke.sh sets the limits when it prepares its admin
identity, so the module passed only after the smoke script had run.

The module now raises virtualserver_antiflood_points_needed_ip_block and
..._command_block itself before its first connection, once per server and
run, through the ServerQuery admin login that refused_moves uses, and clears
the bans of an earlier run with bandelall (banclear is not a command of
either server). The command of the module header works on a fresh stack.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 04:13:13 +03:00
faumarayandClaude Sonnet 5.5 81d1de86e1 Show in the tests that a reconnect's replay is shown again, and what the passing ones prove
a_reconnect_finds_the_state_the_first_session_left passed for a narrower
reason than its comment said: the one message seen before the disconnect is
the newest one, so Dedup (which holds the messages up to 4 s older than the
last one it was asked about) still held it and dropped the host's replay.
With two messages more than 4 s apart the replay of the older one reaches the
user as a live Event::Chat, and no test saw it: the ignored test of the
stored rows used the same one-message setup.

- The ignored replay test is now two, over one scenario: two messages 10 s
  apart are seen, the session ends, a third is said while we are away, a
  second session connects. One asserts that only "while away" is shown (it
  sees ["first", "while away"]), the other that the history has each message
  once (it sees every row twice). The comments of the passing reconnect test
  say what it proves: a message inside Dedup's window is not shown again.
- the_chat_of_a_channel_is_resubscribed_when_we_move_back passed without the
  `seen` check of SessionLink for the same reason (the message seen before is
  the newest one Dedup holds). It now sees two messages 10 s apart before it
  moves away and fails with the check disabled ("before" comes again).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 04:13:13 +03:00
faumarayandClaude Sonnet 5.5 2089f7ceba Record slice 2 in the design of the session seam
Section 16: what the tests on the fake host and the TeamSpeak sessions
cover, the verdict of every case of the conformance suite on both
development servers with the reason it was observed to fail or be skipped,
where the code differs from 9.2 and 9.3 (the CHAT re-subscription is a full
sync, a reconnect resumes nothing, the conformance and live tests are
in-crate), the three things the tests found (our own voice played back, a
session made outside an engine ending by itself, a v1 host's replay stored
twice after a reconnect, the last one open), the protocol and second-half
follow-ups, the deliberately broken translation, and what ran.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 02:29:40 +03:00
faumarayandClaude Sonnet 5.5 226933fcdc Run the link conformance subset and the session scenarios on both TeamSpeak servers
ts_session/live_tests.rs (VOELIN_LIVE=1, the development servers) holds the
TeamSpeak Session tests of docs/session-seam.md section 9.3, made through
TsConnector's plain Connector interface:

- the conformance suite of the protocol repository, every case listed with
  what a TeamSpeak session does with it: two pass (welcome_matches_features,
  close_ends_the_session), four are skipped for a feature the session lacks
  (chat.edit, chat chat.history, idempotency), and the rest do not apply;
  a case the suite gains fails until it is listed;
- what the suite cannot reach: an own-channel message answered and pushed to
  the other session and back, the PASSWORD and FULL refusals of a move, a
  poke between two sessions, voice RTP from one slot to the other session's
  media sink (marker, order, an empty payload at the end), and a channel file
  written with write_file and read back from an offset with read_file.

Two tests, ignored by default, run the cases that do not apply and watch each
fail; the reason in the table is what the case did when it was run.

scripts/it-smoke.sh runs the module before its engine stage.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 02:02:39 +03:00
faumarayandClaude Sonnet 5.5 659798e5f9 Keep the account watches of a session made outside an engine open
A TeamSpeak session made through the plain Connector interface (the way the
conformance suite and any client of the seam that is no engine make one) got
a LocalCtx::standalone() whose only job is to hold the senders of the
myTeamSpeak watches. connect_link dropped that context when it returned, the
senders went with it, and the TeamSpeak link ends its connection with
"account source closed" when a watch has no sender: the session died by
itself a moment after it was handed out. The engine's own path was never
affected, its watches belong to the engine.

The context now moves into the driver task and lives as long as the session.

Found by running the link conformance suite against the development servers:
close_ends_the_session passed vacuously and the_backend_can_end_the_session
saw the session end with that text. The new test fails without this change
("the identity watch lost its sender").

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 02:02:07 +03:00
faumarayandClaude Sonnet 5.5 8d07502e1e Drop the media that comes back on our own slot
A session that loops our voice back (the fake host of the protocol
repository does, so that a test sees media move) made the engine hand our
own packets to the audio thread and show us as talking: the slot map holds
every participant of the server, ourselves included. The engine never plays
itself from the network (a sidetone is local), so on_media returns for the
packets of the slot the host gave us. TeamSpeak never sends a client its own
voice, so nothing changes for the servers the engine reaches today.

Found by the fake-host tests; the test failed before this change with
[1, 50] as the talkers heard (us, then alice).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 01:16:51 +03:00
faumarayandClaude Sonnet 5.5 82da64d8d3 Test the voice path and the conformance suite on the fake host
link/fake_tests.rs holds the tests that need what is private to the crate:

- our voice leaves as RTP on the slot the host gave us (sequence, marker on
  the first packet of a spurt, timestamps that advance by the previous
  packet's duration, an end of spurt that is an empty payload sent once, the
  SSRC that is the flow), read from FakeHandle::sent_media;
- the voice of other slots reaches the audio thread: the talker of the slot,
  a whisper sub-flow, stereo Opus as music, the end of a spurt, and what is
  no voice of a known slot (an unknown slot, probes, feedback) dropped;
- the link conformance suite of the protocol repository, 17 cases, run
  against the session Backends::connect hands over: all pass, none skipped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 01:16:23 +03:00
faumarayandClaude Sonnet 5.5 f9d3f86896 Test the engine on the protocol repository's fake host
tests/session_fake.rs runs the engine through Engine::start_with_backends
with a FakeConnector registered, so a session of the engine is a
voelin_proto::link::Session that no TeamSpeak code made. The host is a
FakeHost filled through put; FakeHandle plays the backend of one session.

The scenarios of link_fake.rs move over (presence until the host ends the
session, commands as v1 requests, a sent message and its echo, the dedup of
a message that comes twice, history across the session), and the ones the
v1 path needs are new: how a session ends and the text the user reads, what
a host refuses and the words it says it in, the chat of a channel
subscribed again when we move back (in full: there is no cursor), closed
scopes, a HostUpdate that changes what the engine asks for, offline messages
as Mail, files through read_file and write_file with a resumed upload, file
operations as FileEntry puts and deletes, the media of a session routed to
the talker of its slot, a reconnect that finds the state the first session
left, and a connect that fails.

link_fake.rs keeps the three tests that need the inner link: the stream
commands (they travel on a port a Session has no part in), the order in
which a reconnect shuts the streams and the old connection down, and a link
that keeps talking after its connection was replaced.

One test is ignored with its reason: a v1 host sends the window of a chat
scope again after a reconnect, and the engine stores the copy (the history
merges copies of different sources only). TeamSpeak never replays, so no
host the engine reaches today meets it; docs/session-seam.md will say so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-24 01:15:34 +03:00
faumarayandClaude Sonnet 5.5 bfc52e2688 Record the third review round in the design of the session seam
Section 15 lists the seven findings with their fix and test, what the fixes
leave as it was (the move shortcut and the window it keeps), and what ran:
format, clippy, tests and the workspace check on 1.94 and nightly, and the
smoke and live runs against fresh dev servers. The other sections say what
changed: the media and push channels have no order between them (4.2 step 9,
13), the second changed test (5.4), the move rule and the transfer deadline
(3.1), the nameless sender (5.2), the address rules (4.2) and the narrowed
features (4.7).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 23:21:07 +03:00
faumarayandClaude Sonnet 5.5 5df011f08c Count only the refusals that come after the host's update in the features test
The last wait of the test asked for file lists until one was refused locally and
took the first refusal on the bus. The asks made before the HostUpdate reached
SessionLink are refused too while the server's list stands, and their events can
still be unread on the bus, so the wait could end before the update had been
applied. It accepts a refusal of a request made after the update only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:45:38 +03:00
faumarayandClaude Sonnet 5.5 2bee828022 Refuse the bookmark addresses that a ts3server:// link would change
The engine hands the TeamSpeak side its bookmark as a ts3server:// link and
reads the options back from it. A link cannot say all an address can: a port
that is no u16 (host:99999) was dropped silently and the connection went to the
default port; a bare host with a '?' in it ended there and hid the channel
behind the next '?' that to_url writes; a '/' or '#' ended the host and a '%'
was decoded. The TeamSpeak library had refused every one of those when it
resolved the address.

connect_params returns a Result now. A bookmark whose port is not a number from
1 to 65535 (in host:port and [v6]:port), or whose host is empty, holds a '?',
'#', '/' or '%', white space or a control character, or has an unclosed '[',
fails the connect with a reason that shows the address without its query. The
other normalisations of the round trip (blanks cut, [v6] without a port read
as v6, an empty option is none, the model's rules for an address that is a
link) are listed in docs/session-seam.md.

Tests: the refused and the accepted addresses (the channel survives the round
trip of each accepted one), the empty options, and a connect with a bad port
that ends in Disconnected with the reason before any link is asked.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:30:03 +03:00
faumarayandClaude Sonnet 5.5 b8db1a85f0 Narrow the features of a session by the server's list
docs/session-seam.md 4.7 says features() is narrowed by Server.features, and
Features::narrowed exists for it, but SessionLink took Session::features() as
it was and a HostUpdate replaced the set wholesale. Against a host whose
server offers fewer features, Capabilities and the local Features::require
refusals were too generous.

SessionLink keeps the host's set and the set of the server (the host's,
narrowed by the Server entity's list; an empty list keeps all of them), and
recomputes the second when the SERVER scope changes or syncs and after a
HostUpdate. Capabilities, the local refusals and the presence fix-ups use it.

Test (over the protocol repository's fake host): a server that lists no files
leaves file transfer out of the capabilities and refuses a file list without
asking the host; an empty list brings it back; a HostUpdate that drops files
takes it away again. It fails on the code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:29:36 +03:00
faumarayandClaude Sonnet 5.5 6a2f00a636 Name a poke from a sender with no unique id who is not on the snapshot
Driver::sender made a synthetic user id for such a sender ("client:N") but put
no User entity into LIVE, so SessionLink::signal found no User and the nick of
the poke was empty. The earlier fix covered senders that have a unique id only.

The driver now puts a bare User with the name the link gave and no uid into
LIVE, keyed by the synthetic client id, before it pushes the signal (so it
shows in no presence, and the poke's from_uid stays none). A client id is given
again to whoever connects next, so the user is replaced when the same client
id comes back with another name; a sender with an empty name gets none.

Test: a poke from client 77 with no unique id is named, and named again with
the new name when the client id comes back as somebody else. It fails on the
code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:29:08 +03:00
faumarayandClaude Sonnet 5.5 b0b1c82ddc Leave the deadline of a transfer's negotiation to the caller
LinkSession gave the reply to an OpenRead or OpenWrite 30 seconds, for every
transfer. Only pictures had a deadline before the seam (IMAGE_NEGOTIATION,
which SessionLink still applies to them); a file the user asked for waited for
a slow server as long as it took. With the extra deadline such a transfer
failed with "timed out", and the inner job stayed in voice.rs until the server
opened it, found nobody to hand the connection to, and dropped it.

The driver waits without a deadline now. A caller that drops the call (the
picture's deadline, a cancel) is noticed through the closed reply channel, and
the driver's wait ends, dropping the receiver that the inner job holds.

Test (virtual time): a read and a write wait 120 seconds for the server and
then open; a read that is dropped closes the reply of the inner job. It fails
on the code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:28:32 +03:00
faumarayandClaude Sonnet 5.5 96dece42e6 Send a move to the link while another move of ours is on its way
Driver::join answered a JoinVoice with the own voice state and sent no Move
whenever the snapshot showed us in the requested channel. A move to another
channel that the link had not answered yet left the snapshot where it was, so
a second request back into the old channel was dropped without an error and
the user ended up in the channel of the first move. The baseline forwarded
every Move to the link (which swallows "already in that channel" itself).

A move into the channel the snapshots show is answered at once only while no
move of ours is pending; otherwise it goes to the link in order. The link says
nothing to a move into the channel it is in, so a refusal of the first move
now also answers the pending moves into the channel the snapshots show,
instead of leaving the second to its ten seconds.

Tests: a move made while another is on its way reaches the link and both are
answered by their snapshots (and a move into the channel we are in is still
answered without the link when none is pending); a move back after a refused
move is answered at once. Both fail on the code before this commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:28:07 +03:00
faumarayandClaude Sonnet 5.5 e06ed43b07 Bind the count in the subscription wait so both rustfmt versions format it alike
Nightly rustfmt wanted `.count()` and `== 3` on separate lines in the wait for
the three subscriptions of a_session_that_ends_during_the_connect_syncs_says_why,
1.94 (which CI pins) did not. The count is a local now, and the comparison a
line of its own. Nightly rustfmt differs from the baseline's six diffs only
(history.rs, encoder.rs, discovery.rs, chat.rs, studio.rs, engine.rs) after it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:26:44 +03:00
faumarayandClaude Sonnet 5.5 6b2b792926 Do not let the fake-link presence test depend on the order of media and pushes
presence_follows_the_link_until_it_disconnects played a voice packet, a poke
and an error in one go and waited for Talking, the poke and the error in that
order. Talking comes from the media queue and the poke and the error from the
push channel, and the loop of SessionLink cannot order two channels: when the
push was polled first the engine reported Poke, Error, Talking, the wait for
Talking skipped the first two and the next wait timed out. It failed in 22 of
300 isolated runs (the baseline never did).

The test now plays the voice packet, waits for Talking, and only then plays the
poke and the error. The design records the change (it is a change of the order
of the steps, not of an assertion).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 22:26:28 +03:00
faumarayandClaude Sonnet 5.5 bf72d85a22 Split the development switches: the sample data into voelin-ui-vm
dev/logic.rs now has the sample of VOELIN_DEMO_UI as plain values and as
the events a server would send: the servers and their presence, the
pictures (PNG bytes the front end saves), the chats with their pins and
topics, the contacts, the private chats, the poke, the offline messages,
the gateway's events, the notices and the recordings, and the older pages
that answer scrolling up. The helpers that only look at the state (the
divider of VOELIN_OPEN=unread, the first locked channel) moved with it. The
Slint side (dev/bind.rs) keeps the switches, the window and the screenshot,
and feeds the sample through the app's own events; a test replays the
whole sample through events::handle and checks the state it leaves.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 13:57:42 +03:00
faumarayandClaude Sonnet 5.5 2d6cbf66af Split the social controller: the friends, the bell, the search and the social events into voelin-ui-vm
social/logic.rs now has the contacts as rows (contact_item, people), the
buttons of a contact and what they ask the window to do next, the bell
(notify, the rows, read, clear, open), the search with what each result
opens, and what an engine event does to the friends, the pokes, the offline
messages and the notices (event). events::handle runs that first, then
events::apply, so a front end has one entry point; Social<D> is the state
those keep, with what the messages page keeps as D for now. Refresh got
people, conversations and dm, the host got dm_shown and now_ms, and
Persist.Settings pages are told apart from the new notices. The Slint side
(social/bind.rs) writes the Bridge, shows the desktop toasts and navigates.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 13:41:29 +03:00
faumarayandClaude Sonnet 5.5 52e39f0b5a Split the settings page controller: the audio form, the switches and the volume dialog into voelin-ui-vm
settings_page/logic.rs now has what the page shows when it opens (the
device choices, the form, the push-to-talk and H.264 switches), what a
change of the form sends to the engine, the microphone test, the push-to-talk
key to register, the crash notice and the H.264 rows, and the client volume
dialog (what it fills from, what it plays and keeps, which client
VOELIN_OPEN=client opens). The audio settings and the clients' volumes are
kept through Persist::Audio and Persist::Playback. The Slint side
(settings_page/bind.rs) lists the devices, owns the hotkey, the codec and
the crash reports, and writes the Bridge.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 13:09:37 +03:00
faumarayandClaude Sonnet 5.5 156df9d95b Split the servers controller: the rail, the card, the tree and the moves into voelin-ui-vm
servers/logic.rs now has what a server does to the state and says in plain
data: which server is shown and forgotten, how it is observed (a plan:
nothing, retry, gateway, query or discover), what finding the gateways
comes to, joining a channel (a move, the password question, or connecting
into it), the members' search, the voice view and the invite link, and the
rail, the server card and the channel tree as rows and values (rail,
toolbar, tree_view, server_tint). The Slint side (servers/bind.rs) keeps
the store, the secrets and the engine commands, and writes the Bridge and
the models from what the logic returns.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 12:57:24 +03:00
faumarayandClaude Sonnet 5.5 02a3b3eab0 Split the chat controller: the chat view, the user's moves and the lines into voelin-ui-vm
chat/logic.rs now has what the chat view shows (the strip, the lines with
their divider and downloads, the pins, the topics and the counts, as plain
data), the lines of a tab or of an open topic (lines_of, also for the Stream
Studio's chat, with the pokes of a private chat's peer), and what the user's
moves do: select and close a tab, send, ask for older messages, mark read,
react, pin, the topics, download, attach and upload. The Slint side
(chat/bind.rs) writes the Bridge and the models from it and calls the
transitions. Poke and its lines moved to voelin_ui_vm::social.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 07:05:58 +03:00
faumarayandClaude Sonnet 5.5 b5ea0c3e95 Send a scope that is bigger than the push channel in bigger chunks
A sync is sent whole or not at all, so that a scope is never left half sent;
that needs the channel to have room for every frame of it. A scope with more
frames than the channel holds when it is empty (more than 16 frames of 256
entities on the smallest channel) could never be sent and stayed lagged for
ever. The chunks of such a sync are now as big as the channel needs, so every
sync fits an empty channel. A test syncs a SERVER scope of 5,000 channels over
the smallest channel.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:53:26 +03:00
faumarayandClaude Sonnet 5.5 0d2ad3f250 Split the streams controller: the state, the events and the rows into voelin-ui-vm
What we share and what we watch are in the AppState now (Sharing, Watching),
with the transitions of the engine's stream events (apply handles them, the
Stream Studio's stream excepted), the user's choices (watch, leave, volume,
quality, the share dialog's plan, the capture that started) and the rows and
texts of the streams panel, the share card and the viewer, as plain data in
streams/logic.rs with tests of their own. The Slint side (streams/bind.rs)
writes the Bridge, owns the capture and the decoder, and attaches or drops
them as an update says (StreamEffects).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:48:18 +03:00
faumarayandClaude Sonnet 5.5 88f58ea468 Record the review round in the design of the session seam
Sections 3, 4.1 to 4.4 and 13 say what changed (notify, the talking hint, the
address text, the close reason of a connect, the chat scope limit and the SyncEnd
of a CHAT scope, the seat across tsclientlib's reconnect), the risk table has the
lagging consumer, and section 14 lists the eight findings with their fix and
test. Follow-ups P13 (a speaking hint for the own channel) and P14 (what a
backend that reconnects inside a session tells its consumer) are for the
protocol repository.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:34:17 +03:00
faumarayandClaude Sonnet 5.5 038f3841df Test the review's fixes through both adapters
Each test fails on the code before the two previous commits (checked against
2d71903 with these tests applied: eleven failures):

- the connection across TeamSpeak's own reconnect: the engine follows a new
  client id (OwnChannel, the chat of the channel, what we say, the voice slot,
  the flags), and stays the client it was while a ghost lingers;
- private messages from 24 peers all arrive;
- a talker the link hears but does not forward as Opus is shown as talking;
- notify refuses what has a stream of its own and runs the rest;
- a session that ends while the connect waits for the syncs says why (a fake
  host that answers the subscriptions and is killed with a reason);
- the text of an address nobody serves keeps the channel password out;
- a consumer that does not read the pushes does not stall the voice, and gets
  the scope again whole when it reads.

The rig can connect as a TeamSpeak 3 server, which is what makes the engine
follow its seat.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:34:17 +03:00
faumarayandClaude Sonnet 5.5 09a0ef3ad5 Make the engine side of the seam report every chat message, follow our seat and believe the host
The review found four defects in SessionLink and the link module, fixed here:

- A message of a CHAT scope's first full sync could be lost. The replica stages
  a full sync until its SyncEnd, so a message of a Change of the sync cannot be
  read when the Change is applied, and SyncBegin, Change and SyncEnd may come
  in different batches; but (channel, id) was marked as reported before the
  replica was asked for the message. A message is marked as reported only when
  it was shown now, and at the SyncEnd of a CHAT scope the messages of that
  channel not shown yet are (two deterministic unit tests, one with SyncEnd in
  a later batch and one for a message that comes before its scope).
- When the push channel ended during the connect syncs, the real close reason
  of the session was thrown away and the engine showed a silent disconnect. It
  now asks closed() (and closes a session that has not ended: a refusal with no
  words).
- The CHAT scopes were limited to 16 whatever the host said. The limit is now
  Welcome.limits.max_chat_subscriptions (0 or none: the v1.0 default of 16); the
  server chat and our channel come first, then the private conversations, the
  newest (highest id) first.
- The own participant was pinned to the one of the connect. Behind a TeamSpeak
  host the seat now follows our user: it stays while the participant is ours
  and moves to the participant that carries our user id when the seat is gone
  (tsclientlib's reconnect makes us another client) or no longer carries it (a
  ghost of the old connection); a seat whose user id changed by itself is
  followed. OwnChannel, the voice flags, the uplink slot and the chat scope of
  our channel follow.

A Signal{speaking} of the host is believed (TalkTracker::hint) until the host
says it is over: that is how a talker whose packets are no Opus is shown as
talking. The documentation of LinkEvent::Talking, OwnChannel and
Connected.own_client says what the adapter derives and what it does not.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:34:00 +03:00
faumarayandClaude Sonnet 5.5 4ddfdef04f Make the TeamSpeak session keep up with a lagging consumer, a reconnect and the contract
The task behind LinkSession (ts_session/driver.rs) is where the review found
five defects, all fixed here:

- It awaited pushes.send() on the bounded push channel, so a consumer that
  lagged stalled the voice media and the commands that share the task. It now
  never waits: a push that finds the channel full is dropped, its scope is
  marked as lagged and sent again whole (SyncBegin .. SyncEnd, all frames or
  none) once the channel has room, as ConnectParams.push_capacity documents; a
  signal has no scope and is dropped. The functions that only awaited the push
  are plain functions now.
- The own client id was the one of the connect for the whole connection, so
  after tsclientlib's own reconnect (a new client id, the same unique id) the
  own channel, the poke target, the own VoiceState, the author of our messages
  and the slot send_media checks were all the old client's. The task now follows
  the snapshots: it stays the client it was while that client is there, and
  else is the newest client of its unique id; the own client keeps the database
  id when an identity is there twice (entities::build), so the user stays the
  same; LinkSession.send_media reads the slot from a shared atomic.
- CHAT subscriptions were limited to 16 in process, so private messages from
  the 15th peer of a connection were never delivered. The limit is 65,536
  (Welcome.limits says so, and the total of subscriptions follows).
- notify accepted List, FileRead and FileWrite and ignored them. Only an op of
  the control stream goes without an answer now (a misplaced op is a Protocol
  error, as on FakeSession); our mute flags go to the link, and any other op is
  run as the request it is. A notify on a session that has closed is refused
  also while the task is still on its way out.
- The link's own Talking was dropped, so a talker whose packets TsLink does not
  forward as Opus (Speex, CELT) was no longer shown as talking. It goes on as a
  Signal{speaking} hint.

The assertion of the Welcome test on the limit follows. The engine side of the
reconnect, the limit and the hint is the next commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:33:17 +03:00
faumarayandClaude Sonnet 5.5 080d8873bb Keep the channel password out of the text of an address no connector serves
Backends::connect handed an address that no plain connector serves to
Connectors::connect, whose error names the whole address: "no connector for
ts3server://host?port=9987&channelpassword=...". The text is shown to the user
and may be logged, and a TeamSpeak link carries the channel password (and a
voelin:// link a host pin) in its query and fragment.

The registry now looks the connector up itself and cuts the address at ? and #
in the text (without_query, which the "not a TeamSpeak server address" error of
the TeamSpeak side uses too, so that one also loses a pin).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:32:19 +03:00
faumarayandClaude Sonnet 5.5 03d1c3bd07 Move the state transition of every engine event that the AppState holds into voelin-ui-vm
events::apply(state, host, event) changes the AppState for an engine Event and
returns an Update: the parts to draw again (Refresh, each once), the status
line, the engine commands, what to keep (Persist), pictures to decode again,
the password dialog, notices for the bell, the chats that changed, a stream to
watch. Host is what a transition asks while it runs (is the chat on screen,
the store's read markers, the preview limit); the Slint client answers it in
host.rs and carries the update out there, so App::handle_event is
social_event, apply_event and social_refresh. The chat transitions (tabs,
messages, what is read, pins and topics, files), the pictures linked in
chats, the server's name, icon and gateway, joining again and the password
prompt, the last place of voice and the stored volumes moved with it; Spot,
the notice types, own_uids and peer_name moved to the view model crate.

Update::rest hands back the events whose state is not in the AppState yet
(the streams we share and watch, the studio's stream, a setting that
changed); the friends, pokes and offline messages are still looked at by
social.rs before and after. The vm tests replay tapes of events against a
fake Host.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 06:30:39 +03:00
faumarayandClaude Sonnet 5.5 0672b21758 Warn about undocumented public items of voelin-ui-vm
#![warn(missing_docs)] on the crate, with the fields and variants that had
no docs documented (BBCode styles and spans, settings, the tree's input) and
a targeted allow on the two mirror modules, bridge and studio_bridge, whose
fields are those of the Slint structs and are explained by the comments in
bridge.slint and studio-bridge.slint.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:55:24 +03:00
faumarayandClaude Sonnet 5.5 12b2773791 Say what docs/ui.md counts, with the true share and the studio's base
The table of controllers still to split now states its measure (every .set_
call, the status line's included), the share of Bridge writes as counted
(four fifths with the status line, two thirds without), the base counts
before the work on voelin-ui-vm (studio.rs 64, settings_pages.rs 52), why the
studio went before streams.rs, and what ImageSource::size() does now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:55:24 +03:00
faumarayandClaude Sonnet 5.5 d9de95b985 Make a picture's size mean it shows, and keep pixels the size they say
ImageSource::size() read a raster file's header, so a cache file that was
cut short or garbled after the header counted as showable, where the Slint
version's decoded image was empty. A raster picture is now decoded to tell
(the first frame, with the limits the Slint side uses) and an SVG must parse
as XML with an svg root (roxmltree, already in the tree through the vector
renderer); the answer is kept per file stamp, and per key and content hash for
a downloaded picture, and decoding runs outside the lock. The size check of
the pixel count no longer overflows on a header that claims u32::MAX.

ImageSource::Rgba holds a Pixels value that can only be made with the right
length, so the Slint conversion cannot hand clone_from_slice bytes that do
not fit (it panics on that).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:52:16 +03:00
faumarayandClaude Sonnet 5.5 f92a14fc84 Fall back to the name's colour for a chat whose server is gone
server_tint answered opaque black for a server that is not in the list,
where the Slint version answered transparent. It now answers none, and the
direct-message list picks the colour of the chat's own title, as it does for
every chat that is not a server's.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 05:31:35 +03:00
faumarayandClaude Sonnet 5.5 2d71903e8f Write two loops of the seam as newer clippy wants them
A nightly clippy (1.101) flags two places of the session seam that the pinned
1.94 does not: the sibling placement of ts_session/entities.rs is a while let
loop, and the generated channel tree of the presence round trip in book.rs
counts with its loop variable. Neither changes behaviour (the same random
stream, the same ids).

The remaining nightly findings are in code this branch does not touch:
audio.rs and media.rs of voelin-core (chunks_exact), voice.rs (a large Err
variant), voelin-audio, voelin-media and voelin-ui.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 02:13:19 +03:00
faumarayandClaude Sonnet 5.5 9bec557c81 Record the second smoke and live runs in the design
The first run of the adapter's smoke failed the stream directory scenario (the
fix is the previous commit); the second ran every per-server scenario of
scripts/it-smoke.sh on TeamSpeak 3 and 6 to the end, and the serial live tests
of voelin-core passed again (live 6, media_live 2, stream_live 3,
voice_features 3). The script's last stage fails as it does on the baseline
(ts6_banners, when the live tests run in parallel).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 01:48:13 +03:00
faumarayandClaude Sonnet 5.5 8c62030e5b Hold the stream task's reports until the engine has announced the connection
The first smoke run of the adapter failed its stream directory scenario (the
late viewer's WatchStream was refused with "not connected with voice"), and an
alternating probe of that scenario with the baseline binary and this one on the
TeamSpeak 6 dev server failed 3 of 6 for this branch and none of the baseline's
four runs the server's clone limit left alone.

The cause is an ordering the adapter lost. The TeamSpeak 6 stream task puts
Event::StreamsChanged on the engine's bus itself; behind a session the engine
hears of the connection only after the connect sequence (several requests
through the driver), while the stream task lists the server's streams as soon as
the server tells it, so a client that acts on the first list asked for a watch
before the engine knew it had voice.

The ts_session driver now holds the bus events of a link with streams that are
no answer to a request until the engine's first stream command (session.rs
sends one in its handling of Connected right after emitting the state), or for
three seconds. Three unit tests pin the hold, its end, and that a link without
streams is not held. The same probe passes 8 of 8; docs/session-seam.md section
13 records it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 01:41:14 +03:00
faumarayandClaude Sonnet 5.5 bc9ccbc85e Measure the voice path through both adapters; test the engine on a registered connector
- A unit test frames 5,000 Opus packets each way through SessionLink, the
  TeamSpeak session and the recording link and prints the cost per packet
  (about 7 microseconds to the host, 10 from it in a debug build; the test
  bounds each direction at 500 microseconds). docs/session-seam.md section 13
  records the figures, which were the one thing slice 1 had not measured.
- tests/session_backends.rs: the engine over voelin-proto's FakeConnector
  through Engine::start_with_backends (connect, server name and backend,
  channels, a move, disconnect), and the registry's error text for an address
  no connector serves.
- The error of a TeamSpeak connector given an address that is not a TeamSpeak
  one no longer prints the query, where a channel password rides.
- The note on the two library tests that need the name localhost to resolve to
  127.0.0.1 says so.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-21 00:41:04 +03:00
faumarayandClaude Sonnet 5.5 1b7abdf4c7 Record slice 1 in the design; consume a host that is no TeamSpeak one
- docs/session-seam.md: the status line, and section 13 with how the code
  differs from the design, a follow-up for the protocol repository (P12), and
  what ran against the baseline.
- docs/architecture.md and the crate docs describe the engine on the Session.
- A departed client's talk state is dropped before the new snapshot replaces
  the table it is looked up in.
- The backend of a host that names none is its product and version.
- A unit test drives the engine over the protocol repository's FakeSession
  through the registry: connect, presence, a move, chat in the channel,
  disconnect.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 22:25:56 +03:00
faumarayandClaude Sonnet 5.5 c473ab216e Run the engine on voelin_proto::link::Session
The engine's voice source is now a voelin_proto::link::Session obtained from a
registry of connectors (docs/session-seam.md, slice 1):

- link::Backends keeps the plain connectors of voelin_proto::link::Connectors
  and the in-process ones that also hand the engine a port for TeamSpeak 6
  streams; the scheme of the address picks the connector, an address without
  one is a TeamSpeak bookmark.
- link::SessionLink is the engine's ServerLink. session.rs is unchanged and
  still speaks LinkCmd and LinkEvent; SessionLink runs the connect sequence
  (List the server, subscribe HOME, SERVER and LIVE, take the seat), keeps a
  voelin_model::replica::Replica, projects it into the client's older model
  (link/project.rs, the fix-ups F1 to F10), frames voice as RTP and derives
  who talks from the media (link/media.rs), and turns every command into the
  Session call of its row. Transfers copy through read_file and write_file.
- ts_session makes a TeamSpeak connection a Session: LinkSession over any
  ServerLink translates the link's commands, events and presence snapshots to
  v1 entities, pushes, answers and RTP; TsConnector makes them for
  ts3server:// and teamspeak:// addresses with TsLink inside, and
  LinkConnector for the link of Engine::start_with_link.
- voice.rs opens the transfer connection itself for the new OpenRead and
  OpenWrite commands; files::download and upload are generic over the stream.
- Engine::start_with_backends is new; start_with and start_with_link go
  through the registry.

tests/link_fake.rs runs through both adapters; its fixtures are normalised as
the design says (an order chain, database ids, talking from media, the server
named, channel chat for the channel we are in), and the request id the link
sees is the session's own. New unit tests cover every row of the mapping with a
recording link, the TeamSpeak session on its own, media framing both ways, the
talk tracker, the close table, the error texts, the backend and capability
tables, the connect parameters, and the presence round trip on book fixtures
and generated presences.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 22:13:07 +03:00
faumarayandClaude Sonnet 5.5 fb8e6b63dd Take voelin-model from VoelinProtocol and add voelin-proto
voelin-identity, voelin-proto and voelin-model now come from one revision of
the protocol repository (main c8e0e5a: the session seam voelin_proto::link
with its account types, and the replica in voelin-model). The client's own
crates/voelin-model is removed: the protocol's crate is a superset, identical
in presence, server, chat and percent, and differs in badges.rs, link.rs and
tree.rs only by a doc comment and two equivalent expressions, and adds the
perms and replica modules. Every crate that used it takes
voelin-model.workspace = true. voelin-core depends on voelin-proto (and, in
its dev-dependencies, on the test-util fakes), which the engine will consume
in the next commits.

Manifests, the lock file and docs only: no source change. THIRD_PARTY_NOTICES.md
is unchanged (scripts/notices.sh --check: up to date).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 21:26:06 +03:00
faumarayandClaude Opus 5.5 38473b761d Design the engine on voelin_proto::link::Session (docs/session-seam.md)
The first half of plan step 7: every LinkCmd, LinkEvent and StreamCmd
variant mapped to the Session API and back, with the decision for what v1
cannot carry yet (streams on a local port, TeamSpeak-only connect options
on the ts3server:// link, presence fix-ups F1-F10 through Foreign);
SessionLink over a Backends registry on the engine side, LinkSession over
TsLink on the TeamSpeak side; connect, close, error texts, Features and
LinkStats; RTP framing of voice against voelin-audio's packets; credentials
with the account left as a hook; files through read_file and write_file;
the FakeLink tests through the adapter, then on FakeSession and FakeHost,
and which conformance cases the TeamSpeak session can run; three slices
with acceptance, and the follow-ups for the protocol repository and for
the move to VoelinGateWay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:47:14 +03:00
224 changed files with 57190 additions and 10299 deletions

No files matched your search

+3 -2
View File
@@ -16,7 +16,8 @@ runs:
- name: apt packages
if: runner.os == 'Linux'
shell: bash
# ALSA (audio devices), fontconfig + xkbcommon (UI), libvpx + dav1d
# ALSA (audio devices), fontconfig + xkbcommon (UI), xkbcommon-x11 + xcb (linked
# by the GPUI front end), libvpx + dav1d
# (video codecs), PipeWire + SPA (screen and audio capture), libclang
# (bindgen), Xvfb (X11 tests).
run: |
@@ -27,7 +28,7 @@ runs:
"${sudo[@]}" apt-get update
"${sudo[@]}" apt-get install -y --no-install-recommends \
build-essential ca-certificates cmake curl git jq pkg-config python3 \
libasound2-dev libfontconfig1-dev libxkbcommon-dev \
libasound2-dev libfontconfig1-dev libxkbcommon-dev libxkbcommon-x11-dev libxcb1-dev \
libvpx-dev libdav1d-dev libpipewire-0.3-dev libspa-0.2-dev libclang-dev \
xvfb xauth
+2
View File
@@ -2,3 +2,5 @@
/dev/.state/
/dist/
/.cargo/
# agent scratch of a worktree (the MAO policy in CLAUDE.md)
/.scratch/
+47 -7
View File
@@ -8,6 +8,24 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Added
- `voelin-gpui`, the GPUI front end of the desktop app, in its first form: a
window titled Voelin with one line of the app's state in it (the version,
the voice connections that are up, the engine events handled, the seconds
up), fed by the same engine and the same view models as the Slint app
(`cargo run -p voelin-gpui --release`), in the Voelin theme: every colour,
radius, size and type token of the Slint app's `theme.slint`, light and dark
(a test reads the Slint file and fails when the two differ), written into
the widget library's theme too, in Inter, with the Slint app's Lucide icons.
`system` mode follows the window's appearance. `VOELIN_OPEN=swatch` shows
every token, a few widgets and the icons (`VOELIN_DEV_THEME`,
`VOELIN_FONT_SCALE`, `VOELIN_WINDOW_SIZE`; screenshots with
`scripts/gpui-shot.sh`, docs/ui/). `VOELIN_METER=1` logs what it costs once a
second: the CPU by group of threads, the memory and its own counters. A
window that cannot open (no driver, no display server) ends the app with
the reason and exit status 1. The Slint app (`voelin`) is unchanged and
stays the app; both run on one engine until the GPUI one reaches parity
(docs/ui.md). It needs Vulkan or OpenGL at run time (Mesa's lavapipe renders
in software); no package ships it yet.
- Log files: each run logs to `<state>/voelin/logs/voelin.log`, the previous
four runs are kept; `VOELIN_LOG` sets what is logged. Settings → Advanced
opens the folder.
@@ -69,13 +87,35 @@ User-visible changes of the apps and the `tsgw` gateway. The format follows
### Changed
- The view models, the app's state and the decisions of the settings pages and
of the Stream Studio moved out of `voelin-ui` into a new crate,
`voelin-ui-vm`, which depends on no UI toolkit (a second front end can use
it); `voelin-ui` converts its plain rows into Slint's and keeps the window,
the Bridge writes and the engine's tasks. The chat formatting reader and the
Twemoji archive moved with them. Nothing changes on screen. See
docs/ui.md, "Two crates".
- The desktop portals (screen capture and camera through PipeWire, the push to
talk shortcut, the file chooser and the proxy settings) talk to D-Bus through
ashpd on `async-io` instead of `tokio`. Nothing changes on screen; the GPUI
front end, which is being built, enables ashpd's `async-io` and ashpd cannot
have both. Every D-Bus connection of the apps, the desktop notifications'
included, now runs on an I/O thread of its own, whichever part of the app
asks first.
- The build needs Rust 1.95 (`rust-toolchain.toml` and the workspace's
`rust-version`; 1.95.0 was used to check it), up from 1.94: the GPUI
front end, which is being built, depends on a library that calls a function
stable since 1.95. Nothing changes in the apps; the gateway's Docker image
builds from `rust:1.95-bookworm`.
- The key store now keeps the device key when signing out of an account,
unbound, whether it was in use before the account or was made for it; "Forget
this device's identity" is the only way a key is deleted. The identity store
also reports a damaged TeamSpeak identity by the kind of damage and never
repeats its key in an error. Nothing changes on screen yet: accounts and
sign-in are later steps.
- The view models, the app's state, the state change of every engine event and
the decisions of the settings pages, the Stream Studio, the streams, the chat,
the servers, the audio settings page, the friends and the development
switches moved out of `voelin-ui` into a new crate, `voelin-ui-vm`, which
depends on no UI toolkit (a second front end can use it); `voelin-ui`
converts its plain rows into Slint's and keeps the window, the Bridge writes
and the engine's tasks. The chat formatting reader and the
Twemoji archive moved with them. Two things change on screen: the chat of
a server that is gone takes the colour of its title instead of opaque
black, and a cached avatar file cut after a valid header shows the
initials instead of a broken picture. See docs/ui.md, "Two crates".
- The identity store keeps identities of more than one kind (TeamSpeak, a Voelin
key, the signed-in account) with the account each belongs to, as a
`voelin-identity` key store, in two database migrations. Existing
+6
View File
@@ -8,6 +8,12 @@ org `Voelin`; the current plan lives in the approved plan file referenced in
`cargo fmt` (hard tabs, `rustfmt.toml`) and `cargo clippy -D warnings` on the
project's own crates (`scripts/own-crates.sh`) green.
Two front ends run on one engine until the second reaches parity:
`crates/voelin-ui` (Slint, the `voelin` binary, the app today) and
`crates/voelin-gpui` (GPUI on an exactly pinned `gpui-kit`, the `voelin-gpui`
binary, under construction); `crates/voelin-ui-vm` holds what they share, the
view models and the state, with no UI toolkit (`docs/ui.md`).
## Hosting: Gitea, not GitHub
- The source of truth is **https://git.faumaray.com** (Gitea). Pull requests,
Generated
+3684 -142
View File
File diff suppressed because it is too large. Load diff
+17 -6
View File
@@ -15,8 +15,8 @@ members = [
"crates/voelin-core",
"crates/voelin-gateway",
"crates/voelin-gateway-proto",
"crates/voelin-gpui",
"crates/voelin-media",
"crates/voelin-model",
"crates/voelin-observer",
"crates/voelin-platform",
"crates/voelin-query",
@@ -37,7 +37,7 @@ default-members = [
"crates/voelin-core",
"crates/voelin-gateway",
"crates/voelin-gateway-proto",
"crates/voelin-model",
"crates/voelin-gpui",
"crates/voelin-observer",
"crates/voelin-platform",
"crates/voelin-query",
@@ -50,7 +50,7 @@ default-members = [
[workspace.package]
edition = "2024"
rust-version = "1.94"
rust-version = "1.95"
license = "MIT OR Apache-2.0"
repository = "https://github.com/Faumaray/Voelin"
publish = false
@@ -59,9 +59,20 @@ publish = false
# The protocol repository is private (VoelinProtocol). This is the SSH URL its
# docs/development.md names, so that a per-developer .cargo/config.toml [patch]
# can point it at a sibling checkout (docs/building.md, "Working with a sibling
# VoelinProtocol checkout"). Pinned by commit until the protocol tags a release
# that has the account-bound KeyStore (its Phase 2 task 28).
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "64808ccbb1e3aa10213392724f2f436bc25fd36f" }
# VoelinProtocol checkout"). Pinned by commit until the protocol tags a release:
# the three crates below are at one revision (main c5bb6b9: the account-bound
# KeyStore whose sign-out keeps every device key and the release of a device key,
# Phase 2 task 34; the account types of the session seam).
voelin-identity = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
# The backend-neutral session seam (`voelin_proto::link`) and the v1 messages.
voelin-proto = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
# The UI-facing domain model and the client's replica of v1 entities.
voelin-model = { git = "ssh://gitea@git.faumaray.com/Voelin/VoelinProtocol.git", rev = "c5bb6b914bdab86eb36f6e32a1a5bc9ac4785562" }
# GPUI, gpui-component and their assets for the GPUI front end (voelin-gpui). Pre-1.0:
# pinned exactly (it pins its `gpui-pre` snapshot exactly too), upgraded in commits of
# their own after rebuilding spikes/gpui on the new release (docs/design/gpui-spikes.md,
# "The version to pin").
gpui-kit = "=0.8.1"
[workspace.lints.rust]
# deny, not forbid: generated code (Slint) needs a local allow.
+8 -1
View File
@@ -28,7 +28,7 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
- `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream
messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes;
see [UPSTREAM.md](crates/proto/UPSTREAM.md))
- `crates/voelin-model`: server flavor detection (TS3 / TS6) and capabilities
- `voelin-model` (from VoelinProtocol, a git dependency): domain model, server flavor detection (TS3 / TS6) and capabilities
- `crates/voelin-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices
- `crates/voelin-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets
- `crates/voelin-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive)
@@ -48,6 +48,11 @@ Done so far (milestones M0–M4 and the first part of M5 of [the plan](docs/arch
- `crates/voelin-ui-vm`: the view models and the app's state behind the UI, with no UI toolkit: engine state
as plain rows and forms, chat formatting, the Twemoji archive, and what the settings pages and the
Stream Studio decide; `voelin-ui` puts them on Slint windows ([docs/ui.md](docs/ui.md))
- `crates/voelin-gpui` (`voelin-gpui`): the GPUI front end, under construction, on the same engine and
view models as the Slint one, which stays the app until it reaches parity: a window with the engine's
state in one line, the Voelin theme (every token of the Slint one's `theme.slint`, light and dark, in
Inter with the same Lucide icons; `VOELIN_OPEN=swatch` shows them) and a cost meter (`VOELIN_METER=1`)
([docs/ui.md](docs/ui.md), "The GPUI front end")
- `crates/voelin-stream`: TeamSpeak 6 streams: stream commands and notifications, JSON signalling,
WebRTC peers (str0m) with host and STUN candidates. A live test streams VP8 + Opus between two
clients through a TS6 server
@@ -79,6 +84,8 @@ The UI (design system, desktop and phone layouts, emoji, how to add a screen) is
```sh
# Desktop app
cargo run -p voelin-ui --bin voelin
# The GPUI front end, under construction (Vulkan or OpenGL at run time)
cargo run -p voelin-gpui --release
# Local servers (use REGISTRY=mirror.gcr.io if Docker Hub rate-limits you)
docker compose -f dev/docker-compose.yml up -d
+3261 -45
View File
File diff suppressed because it is too large. Load diff
+7
View File
@@ -11,6 +11,13 @@ archive in crates/voelin-ui-vm):
- Lucide icons (lucide-static 1.48.0), Copyright (c) Lucide Icons and
Contributors, under the ISC License; the icons derived from Feather are
Copyright (c) 2013-present Cole Bemis, under the MIT License (texts below).
- Lucide icons 1.43.0 (the 1,818 icons of the catalogue of gpui-kit-assets
0.8.1, embedded in the GPUI front end, crates/voelin-gpui, behind the
client's own set above), Copyright (c) Lucide Icons and Contributors, under
the ISC License; the icons derived from Feather are Copyright (c) 2013-present
Cole Bemis, under the MIT License (the same texts, below). The catalogue's
12 other icons are the crate's own, under its Apache-2.0 licence (listed with
the crates).
- Twemoji 15.0 (the emoji images): Twemoji graphics by Twitter, Inc and other
contributors, licensed under CC-BY 4.0
(https://creativecommons.org/licenses/by/4.0/). The SVG files are packed
+4
View File
@@ -23,6 +23,10 @@ accepted = [
"LicenseRef-Slint-Royalty-free-2.0",
# libbz2-rs-sys (unpacks Cisco's OpenH264 download in voelin-media).
"bzip2-1.0.6",
# The GPUI front end: 0BSD (enum-iterator, enum-iterator-derive) and CC0-1.0
# (notify 8, tiny-keccak); see deny.toml.
"0BSD",
"CC0-1.0",
]
# What the apps ship on: the desktop app on Linux (x86_64, and aarch64 for
+1 -1
View File
@@ -19,7 +19,7 @@ tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "sync", "
tracing = "0.1.44"
voelin-core = { path = "../voelin-core" }
# Channels and people for the voice notification.
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
[target.'cfg(target_os = "android")'.dependencies]
anyhow = "1.0.104"
+13 -3
View File
@@ -25,6 +25,8 @@ media-desktop = ["media", "voelin-media/default"]
[dependencies]
anyhow = "1"
base64 = "0.22"
# The RTP packets of the session seam (`voelin_proto::link::MediaPacket`).
bytes = "1"
dirs = "6"
futures = "0.3"
# Finding a server's gateway in DNS (the voice resolver's version).
@@ -50,11 +52,17 @@ toml = "1.1.6"
tracing = "0.1"
voelin-audio = { path = "../voelin-audio", default-features = false }
voelin-gateway-proto = { path = "../voelin-gateway-proto", features = ["client"] }
# `IdentityBlob`, the identity of the API (a TeamSpeak identity as the key store
# keeps it, or a Voelin key).
voelin-identity = { workspace = true }
voelin-media = { path = "../voelin-media", default-features = false }
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
voelin-observer = { path = "../voelin-observer" }
# Paths only (the cache directory).
voelin-platform = { path = "../voelin-platform", default-features = false }
# The backend-neutral session seam the engine consumes (`voelin_proto::link`)
# and the v1 messages it speaks.
voelin-proto = { workspace = true }
voelin-query = { path = "../voelin-query" }
voelin-store = { path = "../voelin-store" }
voelin-stream = { path = "../voelin-stream" }
@@ -65,13 +73,15 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
tsproto-types = { path = "../proto/tsproto-types" }
[dev-dependencies]
# An HTTP/2 connection in a test (both already in the tree through h2).
bytes = "1"
# An HTTP/2 connection in a test (already in the tree through h2).
http = "1"
# Already in the app's graph (reqwest); for one_rustls_crypto_provider.
rustls = { version = "0.23", default-features = false }
# `process`: the browser interop test drives Chromium through Node.js.
tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] }
# The fakes of the session seam (`FakeHost`, `FakeSession`, the conformance
# suite).
voelin-proto = { workspace = true, features = ["test-util"] }
[lints]
workspace = true
+25 -5
View File
@@ -4,21 +4,21 @@
//! id (the CRC32 of the image, as TeamSpeak assigns them), so a lookup is a
//! map access, and the same image seen on several servers or under
//! several clients is one file. Pictures from the web (banners,
//! [`crate::web`]) are named by the MD5 hash of their address. Keys are
//! `web`) are named by the MD5 hash of their address. Keys are
//! relative paths (`avatars/<md5>`, `icons/<id>`, `pictures/<md5>`).
//!
//! The cache is bounded by `cache.max_mb` (read on every insert; 0: no
//! limit): the least recently used files go first. Use times survive
//! restarts as the files' modification times.
//!
//! Downloads are deduplicated: [`Cache::fetch`] tells the first asker to
//! Downloads are deduplicated: `Cache::fetch` tells the first asker to
//! download (into a temporary path), later askers wait for the same
//! download ([`Cache::finish`] answers them all).
//! download (`Cache::finish` answers them all).
//!
//! A picture from the web keeps its host's validators (`ETag`,
//! `Last-Modified`) next to it, in `validators/pictures/<md5>`: asked for
//! again, it is downloaded only if it changed ([`Cache::validators`],
//! [`Arrived::Unchanged`]).
//! again, it is downloaded only if it changed (`Cache::validators`,
//! `Arrived::Unchanged`).
use std::collections::{BTreeMap, HashMap};
use std::fmt;
@@ -184,6 +184,17 @@ pub(crate) const MAX_PICTURE_BYTES: u64 = 128 << 20;
/// does not hold a download slot.
pub(crate) const MIN_PICTURE_RATE: u64 = 8 << 10;
/// How long a picture of `size` bytes may take to arrive: a minute, plus
/// its size at [`MIN_PICTURE_RATE`], so large banners arrive on slow
/// links while a stalled transfer still ends.
pub(crate) fn image_download_time(size: u64) -> std::time::Duration {
std::time::Duration::from_secs(60 + size / MIN_PICTURE_RATE)
}
/// How long the server may take to start an image transfer (a busy server
/// answers the requests of a large channel tree in turn).
pub(crate) const IMAGE_NEGOTIATION: std::time::Duration = std::time::Duration::from_secs(30);
/// The cache key of a picture on the web: only `http` and `https`
/// addresses (blanks around one are not part of it).
pub(crate) fn picture_key(url: &str) -> Option<String> {
@@ -489,6 +500,15 @@ mod tests {
use super::*;
#[test]
fn large_pictures_get_time_to_arrive() {
let secs = std::time::Duration::from_secs;
assert_eq!(image_download_time(0), secs(60));
assert_eq!(image_download_time(100 << 10), secs(72));
// The largest picture, at the slowest rate allowed.
assert_eq!(image_download_time(MAX_PICTURE_BYTES), secs(60 + 16384));
}
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"voelin-cache-{tag}-{}-{:?}",
+7 -2
View File
@@ -453,10 +453,15 @@ mod tests {
lookups
}
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
/// `lookups` asking the real `/.well-known/tsgw` at `port`. A name is
/// connected to through the system's resolver, except `localhost`: the
/// servers of the tests listen on 127.0.0.1, and some machines resolve
/// `localhost` to `::1` only. (The test cares that the gateway is asked at
/// the name `localhost`, not what the resolver makes of it.)
fn probing(mut lookups: Lookups, port: u16) -> Lookups {
lookups.probe = Arc::new(move |name| {
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok()?.ok() }.boxed()
let host = if name == "localhost" { "127.0.0.1".to_owned() } else { name };
async move { timeout(PROBE_TIMEOUT, well_known(&host, port)).await.ok()?.ok() }.boxed()
});
lookups
}
+41 -30
View File
@@ -32,13 +32,13 @@
//! never downloaded). [`crate::Command::SetAvatar`] uploads our own.
use std::fmt;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use serde::Serialize;
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt, AsyncWrite, AsyncWriteExt};
/// Picked by the caller; the answer carries it back.
pub type RequestId = u64;
@@ -168,9 +168,10 @@ impl Progress<'_> {
const CHUNK: usize = 64 * 1024;
/// Receive a file: `size` bytes in total, `offset` of them already in the
/// sink. Reports `Started`, `Progress` and the final state.
pub(crate) async fn download(
mut stream: TcpStream,
/// sink; `stream` carries the rest. Reports `Started`, `Progress` and the
/// final state.
pub(crate) async fn download<R: AsyncRead + Unpin>(
mut stream: R,
size: u64,
offset: u64,
sink: Sink,
@@ -185,8 +186,8 @@ pub(crate) async fn download(
});
}
async fn receive(
stream: &mut TcpStream,
async fn receive<R: AsyncRead + Unpin>(
stream: &mut R,
size: u64,
offset: u64,
sink: &Sink,
@@ -198,19 +199,22 @@ async fn receive(
let mut done = offset;
match sink {
Sink::File { part, dest, append } => {
// The directory and the file are made in one step, without a pause in
// which the task could be stopped: a cancel stops the task, waits for
// it and then removes the part file, so what the task made must be
// there by then (a pending open on the blocking pool would not be).
if let Some(dir) = part.parent().filter(|d| !d.as_os_str().is_empty()) {
tokio::fs::create_dir_all(dir)
.await
.map_err(|e| format!("{}: {e}", dir.display()))?;
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
.append(*append)
.truncate(!*append)
.open(part)
.await
.map_err(|e| format!("{}: {e}", part.display()))?;
let mut file = tokio::fs::File::from_std(
std::fs::OpenOptions::new()
.create(true)
.write(true)
.append(*append)
.truncate(!*append)
.open(part)
.map_err(|e| format!("{}: {e}", part.display()))?,
);
let received = async {
while done < size {
let n = stream.read(&mut buf).await.map_err(|e| e.to_string())?;
@@ -253,26 +257,34 @@ async fn receive(
}
}
/// Send `file` from `offset` (`size` bytes in total). Reports `Started`,
/// `Progress` and the final state.
pub(crate) async fn upload(
mut stream: TcpStream,
/// Send `file` from `offset` (`size` bytes in total) into `writer`, then end
/// it and wait for `stored`, which resolves once the server has the file.
/// Reports `Started`, `Progress` and the final state.
pub(crate) async fn upload_to<W, F>(
mut writer: W,
stored: F,
file: PathBuf,
size: u64,
offset: u64,
progress_every: Duration,
report: Report,
) {
) where
W: AsyncWrite + Unpin,
F: Future<Output = Result<(), String>>,
{
report(TransferState::Started { size, offset });
let result = send(&mut stream, &file, size, offset, progress_every, &report).await;
let result = match send(&mut writer, &file, size, offset, progress_every, &report).await {
Ok(()) => stored.await,
Err(e) => Err(e),
};
report(match result {
Ok(()) => TransferState::Done { size, path: Some(file), data: None },
Err(e) => TransferState::Failed(e),
});
}
async fn send(
stream: &mut TcpStream,
async fn send<W: AsyncWrite + Unpin>(
stream: &mut W,
path: &Path,
size: u64,
offset: u64,
@@ -300,8 +312,6 @@ async fn send(
}
stream.flush().await.map_err(|e| e.to_string())?;
stream.shutdown().await.map_err(|e| e.to_string())?;
// The server closes the connection once it has everything.
let _ = tokio::time::timeout(Duration::from_secs(30), stream.read(&mut buf[..1])).await;
Ok(())
}
@@ -421,7 +431,7 @@ fn percent_decode(text: &str) -> Option<String> {
mod tests {
use std::sync::Mutex;
use tokio::net::TcpListener;
use tokio::net::{TcpListener, TcpStream};
use super::*;
@@ -562,7 +572,8 @@ mod tests {
});
let (report, states) = recorder();
let stream = TcpStream::connect(addr).await.unwrap();
upload(stream, file.clone(), 10, 4, Duration::ZERO, report).await;
let (_, write) = tokio::io::split(stream);
upload_to(write, async { Ok(()) }, file.clone(), 10, 4, Duration::ZERO, report).await;
assert_eq!(server.await.unwrap(), b"456789");
assert!(matches!(states.lock().unwrap().last(), Some(TransferState::Done { .. })));
assert_eq!(md5_file(&file).unwrap(), "781e5e245d69b566979b86e28d23f2c7");
+44 -19
View File
@@ -61,6 +61,7 @@ use voelin_gateway_proto::{
HistoryEntry, HistoryQuery, PermRule, PermRuleInfo, PinInfo, RsvpStatus, StreamEntry,
StreamSpec, TopicInfo, UserRef,
};
use voelin_identity::IdentityBlob;
use voelin_model::{ChannelId, ChatTarget, Presence};
use voelin_store::WriteOutcome;
@@ -91,13 +92,23 @@ pub(crate) enum GatewayEvent {
Disconnected(Option<String>),
}
/// The TeamSpeak identity of a blob, or why a gateway cannot be logged in to
/// with it.
fn login_identity(blob: &IdentityBlob) -> Result<tsclientlib::Identity, String> {
crate::ts::identity::from_blob(blob).map_err(|e| e.to_string())
}
/// Connect to a gateway (`ws://…/v1` or `wss://…/v1`) and log in with a
/// TeamSpeak identity.
/// TeamSpeak identity (a blob of kind `teamspeak`, see
/// [`crate::ts::identity::to_blob`]; one that is none is refused as
/// [`ErrorCode::AuthFailed`], the way the gateway would).
pub async fn connect(
url: &str,
identity: &tsclientlib::Identity,
identity: &IdentityBlob,
) -> Result<(GatewayClient, mpsc::UnboundedReceiver<Push>), ClientError> {
connect_watched(url, identity, &Progress::default()).await
let identity = login_identity(identity)
.map_err(|message| ClientError::Gateway { code: ErrorCode::AuthFailed, message })?;
connect_watched(url, &identity, &Progress::default()).await
}
/// [`connect`], telling `progress` each step (for the log).
@@ -114,10 +125,19 @@ async fn connect_watched(
/// logs in.
pub(crate) async fn run(
mut urls: Vec<String>,
identity: tsclientlib::Identity,
identity: IdentityBlob,
mut commands: mpsc::UnboundedReceiver<GatewayCmd>,
events: mpsc::UnboundedSender<GatewayEvent>,
) {
// An identity that cannot be read will not be tomorrow: like a refused login.
let identity = match login_identity(&identity) {
Ok(identity) => identity,
Err(reason) => {
debug!(%reason, "gateway: the identity cannot be read");
let _ = events.send(GatewayEvent::Disconnected(Some(reason)));
return;
}
};
// A gateway that is away (down, restarting, a network change, a proxy
// in front of it that fails) or cannot log us in yet (it does not know
// the identity before voice connected once, its server is restarting)
@@ -274,20 +294,24 @@ pub(crate) struct Observed {
}
impl Observed {
pub(crate) fn new(urls: &[String], identity: &tsclientlib::Identity) -> Self {
Self {
urls: urls.to_vec(),
key: identity.key().to_pub().to_ts(),
counter: identity.counter(),
nudged: None,
pub(crate) fn new(urls: &[String], identity: &IdentityBlob) -> Self {
let (key, counter) = Self::of(identity);
Self { urls: urls.to_vec(), key, counter, nudged: None }
}
/// The public key and the counter of an identity: an identity that cannot be
/// read has neither (and so is the same as any other that cannot).
fn of(identity: &IdentityBlob) -> (String, u64) {
match login_identity(identity) {
Ok(identity) => (identity.key().to_pub().to_ts(), identity.counter()),
Err(_) => (String::new(), 0),
}
}
/// Whether this is what is observed with.
pub(crate) fn same(&self, urls: &[String], identity: &tsclientlib::Identity) -> bool {
self.urls == urls
&& self.counter == identity.counter()
&& self.key == identity.key().to_pub().to_ts()
pub(crate) fn same(&self, urls: &[String], identity: &IdentityBlob) -> bool {
let (key, counter) = Self::of(identity);
self.urls == urls && self.counter == counter && self.key == key
}
/// Whether to try again now ([`GatewayCmd::RetryNow`]): not twice
@@ -1182,15 +1206,16 @@ mod tests {
#[test]
fn the_same_observation_is_nudged_at_most_every_5_s() {
let blob = crate::ts::identity::to_blob;
let identity = tsclientlib::Identity::create();
let urls = vec!["ws://gw.example.test:7788/v1".to_owned()];
let mut observed = Observed::new(&urls, &identity);
assert!(observed.same(&urls, &identity));
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &identity));
assert!(!observed.same(&urls, &tsclientlib::Identity::create()));
let mut observed = Observed::new(&urls, &blob(&identity));
assert!(observed.same(&urls, &blob(&identity)));
assert!(!observed.same(&["wss://gw.example.test/v1".to_owned()], &blob(&identity)));
assert!(!observed.same(&urls, &blob(&tsclientlib::Identity::create())));
// Its security level raised: logged in with the new counter.
let raised = tsclientlib::Identity::new(identity.key().clone(), identity.counter() + 1);
assert!(!observed.same(&urls, &raised));
assert!(!observed.same(&urls, &blob(&raised)));
let now = Instant::now();
assert!(observed.nudge_at(now));
assert!(!observed.nudge_at(now + Duration::from_secs(4)));
+27 -64
View File
@@ -3,8 +3,10 @@
//! The UI talks to an [`Engine`] with [`Command`]s and receives [`Event`]s.
//! Each server the user works with is a session with up to three sources:
//!
//! - **voice**: a normal client connection (visible, can talk), made by a
//! [`link::ServerLink`] ([`TsLink`] for TeamSpeak servers; see [`link`])
//! - **voice**: a normal client connection (visible, can talk): a
//! `voelin_proto::link::Session` that the connector of the server's address
//! makes ([`Backends`], and [`ts::TsConnector`] for TeamSpeak servers; see
//! [`link`])
//! - **gateway**: a `tsgw` gateway (invisible presence, relayed chat)
//! - **query**: the user's own ServerQuery credentials (same, without a gateway)
//!
@@ -17,9 +19,9 @@
//! [`Engine::subscribe_frames`] for the frames of watched streams. The audio
//! of watched streams plays through the session's speakers by itself
//! ([`Command::SetStreamVolume`]); capture, encoding and decoding of video
//! are in [`media`] (feature `media`), and the Stream Studio (scenes of
//! are in `media` (feature `media`), and the Stream Studio (scenes of
//! sources composited into one stream, recording, a replay buffer, WHIP) in
//! [`studio`].
//! `studio`.
//!
//! Settings are a [`settings::Settings`] service: typed keys, runtime
//! values stored in the client database ahead of command line, config file
@@ -46,14 +48,12 @@
//! volume) are engine-wide ([`contacts`]).
mod audio;
mod book;
pub mod cache;
pub mod contacts;
pub mod discover;
pub mod files;
pub mod gateway;
pub mod history;
pub mod identity;
pub mod link;
#[cfg(feature = "media")]
pub mod media;
@@ -66,16 +66,14 @@ pub mod stream;
mod stream_types;
#[cfg(feature = "media")]
pub mod studio;
mod ts_link;
pub mod versions;
mod voice;
pub mod ts;
mod web;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc, watch};
use tokio::sync::{broadcast, mpsc};
pub use voelin_audio::settings::TransmitMode;
pub use voelin_audio::{AudioSettings, ProcessingSettings, VadSettings};
use voelin_model::{
@@ -91,15 +89,14 @@ pub use files::{Bytes, DownloadTo, FileEntry, RequestId, TransferId, TransferSta
pub use gateway::{GatewayRequest, GatewayUpdate};
use history::SharedHistory;
pub use history::{History, HistoryMessage, HistorySource};
pub use link::ConnectOptions;
pub use link::ConnectOptions as VoiceOptions;
pub use link::ServerLink;
pub use link::{Backends, VoiceOptions};
pub use offline::{OfflineMessage, OfflineMessageInfo};
pub use query::{QueryLogin, QueryTransport};
pub use route::{ChatRoute, Dedup, route_chat};
use settings::{SettingChange, Settings, SharedSettings};
use stream::{EncodedFrame, LayerId, LayerSpec, StreamInfo, StreamSetup, ViewerInfo};
pub use stream::{StreamFrame, StreamSink, StreamState, WatchState};
pub use ts_link::TsLink;
pub use voelin_identity::IdentityBlob;
/// Banners are downloaded and shown by the same rule.
pub use web::is_svg;
/// Pictures from the web go through the desktop's proxy (set at startup).
@@ -114,13 +111,6 @@ pub const POKE_MESSAGE_MAX: usize = 100;
/// What the UI asks for.
#[derive(Clone, Debug)]
pub enum Command {
/// Main account proof for every current and future voice connection.
SetMytsIdentity(Option<Arc<tsproto::myts::Identity>>),
/// What voice servers are shown of the main account (its avatar and
/// badges with their certificates, its User Tag; TeamSpeak 6): sent to
/// every connection that presents the account's myTS ID, once connected
/// and when it changes; cleared on a sign-out.
SetMytsData(Option<Arc<tsclientlib::MytsData>>),
ConnectVoice {
session: SessionId,
options: Box<VoiceOptions>,
@@ -136,12 +126,15 @@ pub enum Command {
ObserveGateway {
session: SessionId,
urls: Vec<String>,
identity: Box<tsclientlib::Identity>,
/// The TeamSpeak identity to log in with ([`ts::identity::to_blob`]).
/// One that is none, or cannot be read, ends the observation with
/// its reason.
identity: Box<IdentityBlob>,
},
/// Invisible presence and relay chat with own ServerQuery credentials.
ObserveQuery {
session: SessionId,
connect: Box<voelin_query::Connect>,
connect: Box<QueryLogin>,
},
StopObserving {
session: SessionId,
@@ -276,7 +269,7 @@ pub enum Command {
},
/// The video of a watched stream arrives, but none of it decodes: watch
/// it in another codec the streamer offered, if there is one (a new
/// connection without this one). [`media::Viewer`] sends it.
/// connection without this one). `media::Viewer` sends it.
StreamUndecodable {
session: SessionId,
stream_id: String,
@@ -792,19 +785,18 @@ impl Engine {
}
/// Start the engine on the current tokio runtime with `settings` and
/// chat `history`, connecting voice with [`TsLink`].
/// chat `history`, connecting voice with the engine's own connectors
/// ([`Backends::default`]: TeamSpeak 3 and 6).
pub fn start_with(settings: Settings, history: History) -> Self {
Self::start_with_link(settings, history, Arc::new(TsLink))
Self::start_with_backends(settings, history, Backends::default())
}
/// Start the engine on the current tokio runtime with `settings` and
/// chat `history`, connecting voice with `link` (every session's voice
/// source is one of its connections, see [`link`]).
pub fn start_with_link(
settings: Settings,
history: History,
link: Arc<dyn ServerLink>,
) -> Self {
/// chat `history`, connecting voice with the connectors in `backends`:
/// the one for the scheme of a session's address makes its
/// `voelin_proto::link::Session`.
pub fn start_with_backends(settings: Settings, history: History, backends: Backends) -> Self {
let link = Arc::new(link::SessionLink::new(backends));
let (commands, rx) = mpsc::unbounded_channel();
let (events, _) = broadcast::channel(4096);
// About a minute of one watched stream.
@@ -900,14 +892,12 @@ async fn run(
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
engine: Shared,
link: Arc<dyn ServerLink>,
link: Arc<link::SessionLink>,
) {
let Shared { settings: shared, history, cache, contacts } = engine.clone();
// Before any command: a contact set meanwhile would be lost.
contacts.load().await;
let mut sessions: HashMap<SessionId, session::SessionHandle> = HashMap::new();
let (myts_identity, _) = watch::channel(None);
let (myts_data, _) = watch::channel(None);
let mut current = shared.current();
// Pruning: at start, then hourly (and when the setting changes).
let mut prune = tokio::time::interval(std::time::Duration::from_secs(3600));
@@ -952,29 +942,6 @@ async fn run(
},
};
let id = match command {
Command::SetMytsIdentity(identity) => {
// Still no account is no change: every notification restarts
// handshakes and sends `updatemytsid` on every connection. Any
// account is (each connection's proof is signed anew).
myts_identity.send_if_modified(|current| {
if current.is_none() && identity.is_none() {
return false;
}
*current = identity;
true
});
continue;
}
Command::SetMytsData(data) => {
myts_data.send_if_modified(|current| {
if *current == data {
return false;
}
*current = data;
true
});
continue;
}
Command::SetAudioSettings(new) => {
settings = (*new).clone();
for s in sessions.values() {
@@ -1051,8 +1018,6 @@ async fn run(
settings.clone(),
engine.clone(),
link.clone(),
myts_identity.subscribe(),
myts_data.subscribe(),
);
if let Some(profiles) = &srtp_profiles {
s.send(Command::SetSrtpProfiles(profiles.clone()));
@@ -1131,9 +1096,7 @@ fn command_session(command: &Command) -> SessionId {
| Command::DeleteOfflineMessage { session, .. }
| Command::SetOfflineMessageRead { session, .. }
| Command::CloseSession { session } => *session,
Command::SetMytsIdentity(_)
| Command::SetMytsData(_)
| Command::SetAudioSettings(_)
Command::SetAudioSettings(_)
| Command::SetSrtpProfiles(_)
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
-330
View File
@@ -1,330 +0,0 @@
//! The seam between a session and the server it talks to as a client.
//!
//! A session merges up to three sources (voice, gateway, query). The *voice*
//! source is the connection that is visible on the server, can talk and
//! carries chat, files, pokes, offline messages and streams. Everything the
//! session needs from it goes through [`ServerLink`]: the session hands the
//! link the connection's options and a [`LinkCtx`], and talks to it with two
//! channels, [`LinkCmd`]s in and [`LinkEvent`]s out. Nothing else of the
//! backend shows: the session merges, deduplicates, stores and routes what a
//! link reports, whichever server software is behind it.
//!
//! # Contract for a link
//!
//! - [`ServerLink::spawn`] returns at once; the connection runs on its own
//! task and reports through `events`. Connecting is not an event: the
//! session shows `Connecting` from the moment it spawned the link, until
//! [`LinkEvent::Connected`] (or [`LinkEvent::Disconnected`] if it failed).
//! - The first thing a connected link reports is [`LinkEvent::Connected`]
//! (name, backend, what it can do, our client id, the server's unique id),
//! then [`LinkEvent::Presence`] whenever anything in the server's tree or
//! client list changed (a full snapshot each time) and
//! [`LinkEvent::OwnChannel`] when we moved.
//! - [`LinkEvent::Disconnected`], with the reason if it was not asked for,
//! reports that the connection ended, whichever way it did; a link sends it
//! once, and nothing from the connection itself follows it. A link that
//! gets [`LinkCmd::Disconnect`] (or whose command channel closes) leaves.
//! It is not promised to be the last event of the link: the stream task of
//! a connection with streams is a task of its own, which winds down after
//! the connection, so [`LinkEvent::OwnStream`] (`Ended`) and
//! [`LinkEvent::StreamAudioEnded`] from it, and the bus events of its
//! streams, may follow `Disconnected` (`TsLink` ends the stream task as the
//! connection's loop ends, which usually, not always, puts them before it).
//! The session does not depend on the order: it ends our own stream and
//! the audio of watched streams itself when it hears `Disconnected`, and
//! ignores what a link says after that, like the events of a replaced one.
//! - Streams (screen sharing) are the link's business from the capabilities
//! on: when [`Capabilities::streams`] is set in `Connected`, it runs the
//! stream task, takes [`LinkCmd::Stream`] and reports through the event
//! bus ([`LinkCtx::emit`]) like the other answers that need not pass the
//! session first (file lists, transfers, offline messages, stream state).
//! What the session must place itself comes as events: our own stream's
//! life ([`LinkEvent::OwnStream`], for the gateway directory) and the audio
//! of watched streams ([`LinkEvent::StreamAudio`], for the audio thread,
//! and [`LinkEvent::StreamAudioEnded`] when a stream's audio is over).
//! When the session replaces a connection it gives the old link
//! `StreamCmd::Shutdown` before [`LinkCmd::Disconnect`] (the streams hear
//! of their end before the link stops reading commands).
//! - What the session must see first (chat, pokes, who is talking, audio)
//! comes as [`LinkEvent`]s; the answers to requests the UI made (a file
//! list, a request's `Done`) go straight to the event bus with
//! [`LinkCtx::emit`].
//! - Events of a link the session replaced are ignored (each link has a
//! generation), so a link need not stop emitting at once.
//!
//! # Implementations
//!
//! [`TsLink`](crate::TsLink) (`ts_link.rs`, with `voice.rs`) is the
//! TeamSpeak 3 and 6 connection of `tsclientlib`; it is the only one for now,
//! and [`Engine::start_with_link`](crate::Engine::start_with_link) takes
//! another (the tests drive the session with an in-memory one,
//! `tests/link_fake.rs`). The decoupling plan moves `TsLink` out of this
//! crate into the TeamSpeak gateway (VoelinGateWay, `voelin-gateway-ts`), and
//! the Voelin protocol's QUIC transport becomes the other implementation,
//! both behind the backend-neutral `voelin_proto::link::Session` of
//! VoelinProtocol; `ServerLink` is this crate's side of that seam until then.
//!
//! # What is still TeamSpeak's
//!
//! The seam is not backend-neutral yet. What still has TeamSpeak types or
//! TeamSpeak's shape, and changes when `TsLink` leaves:
//!
//! - Types of the TeamSpeak crates: [`ConnectOptions::identity`] and
//! [`ConnectOptions::client_version`] (`tsclientlib`), and the account
//! proof in [`LinkCtx`] (`myts_identity` of `tsproto`, `myts_data` of
//! `tsclientlib`).
//! - Client ids are TeamSpeak's `u16`: `own_client` of
//! [`LinkEvent::Connected`], `from` of [`LinkEvent::Poke`], `client` of
//! [`LinkEvent::Talking`] and of [`LinkCmd::Poke`], the `author_id` of a
//! [`ChatMessage`], and the viewer and streamer ids of the stream API.
//! - [`LinkEvent::Presence`] snapshots have TeamSpeak's shape: `u16` client
//! ids, `u64` channel and group ids, server and channel groups, talk
//! power, icons, badges and the myTeamSpeak avatar.
//! - The stream vocabulary is that of `voelin-stream`, the TeamSpeak 6 stream
//! protocol: `PeerConfig` in [`ConnectOptions::stream_peer`], `MediaFrame`
//! in the frames of watched streams ([`LinkCtx`]), `VideoFormat` in
//! `StreamCmd::VideoFrame`, and `VideoCodec` and `FrameSource` of the same
//! API (re-exported from [`crate::stream`]).
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc, watch};
use voelin_audio::{EncodedVoice, VoicePacket};
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence};
use voelin_stream::PeerConfig;
use crate::files::{Report, RequestId, Sink, TransferId};
use crate::settings::SharedSettings;
use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame};
use crate::{BackendInfo, Event, SessionId};
/// Starts the voice connection of a session.
///
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
/// one connection.
pub trait ServerLink: Send + Sync + 'static {
/// Connect to the server `options` names and run the connection on its
/// own task: take commands from `cmds`, report through `events`, and end
/// the connection with [`LinkEvent::Disconnected`]. Does not block.
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
);
}
/// What a connection needs to know: the server, who to be, where to join.
/// ([`VoiceOptions`](crate::VoiceOptions) is the name the app uses for it.)
#[derive(Clone, Debug)]
pub struct ConnectOptions {
pub address: String,
pub nickname: String,
/// The identity to connect with (TeamSpeak's, for now).
pub identity: Option<tsclientlib::Identity>,
/// Signed compatibility version; `None` selects the native platform's tuple.
pub client_version: Option<tsclientlib::Version>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections (TeamSpeak 6).
pub stream_peer: PeerConfig,
}
impl ConnectOptions {
pub fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
Self {
address: address.into(),
nickname: nickname.into(),
identity: None,
client_version: None,
server_password: None,
channel: None,
channel_password: None,
token: None,
audio: false,
stream_peer: PeerConfig::default(),
}
}
}
/// What the engine gives a link besides the options: where the connection
/// answers the requests the session need not see, and what it shares with
/// the session's other parts.
#[derive(Clone)]
pub struct LinkCtx {
pub(crate) session: SessionId,
pub(crate) events: broadcast::Sender<Event>,
/// The frames of watched streams (kept off the event bus).
pub(crate) frames: broadcast::Sender<StreamFrame>,
pub(crate) settings: SharedSettings,
/// The main account's proof, for every connection ([`crate::Command::SetMytsIdentity`]).
pub(crate) myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
/// What the server is shown of the account ([`crate::Command::SetMytsData`]).
pub(crate) myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
}
impl LinkCtx {
/// The session this connection belongs to.
pub fn session(&self) -> SessionId {
self.session
}
/// Tell the engine's event bus something (a request's answer, a
/// transfer's progress).
pub fn emit(&self, event: Event) {
let _ = self.events.send(event);
}
pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) {
self.emit(Event::RequestDone { session: self.session, request, result });
}
}
/// A file on the server: channel, its password, path.
#[derive(Clone, Debug)]
pub struct Remote {
pub channel: ChannelId,
pub password: Option<String>,
pub path: String,
}
/// What the session asks of a connection.
pub enum LinkCmd {
SendChat(ChatTarget, String),
Move(ChannelId, Option<String>),
SetInputMuted(bool),
SetOutputMuted(bool),
/// An encoded voice frame from the audio thread.
Audio(EncodedVoice),
/// A stream command; the link answers on the event bus. Only sent while
/// the connection's capabilities include streams.
Stream(StreamCmd),
Poke {
client: u16,
message: String,
},
ListFiles {
request: RequestId,
dir: Remote,
},
/// Download `file`; `transfer` if the user can cancel it.
Download {
transfer: Option<TransferId>,
file: Remote,
sink: Sink,
report: Report,
},
Upload {
transfer: Option<TransferId>,
file: Remote,
from: PathBuf,
overwrite: bool,
resume: bool,
report: Report,
},
CancelTransfer(TransferId),
DeleteFiles {
/// `None`: best effort, nobody waits for the answer.
request: Option<RequestId>,
channel: ChannelId,
password: Option<String>,
paths: Vec<String>,
},
RenameFile {
request: RequestId,
from: Remote,
to: Remote,
},
CreateDirectory {
request: RequestId,
dir: Remote,
},
/// Announce our avatar's hash (empty: no avatar).
SetAvatarHash {
request: Option<RequestId>,
hash: String,
},
OfflineList {
request: RequestId,
},
OfflineGet {
request: RequestId,
id: u32,
},
OfflineAdd {
request: RequestId,
to_uid: String,
subject: String,
text: String,
},
OfflineDelete {
request: RequestId,
id: u32,
},
OfflineFlag {
request: RequestId,
id: u32,
read: bool,
},
Disconnect,
}
/// What a connection tells the session.
pub enum LinkEvent {
Connected {
name: String,
/// The server software, and what it can do (the connection knows
/// both from the server's version).
backend: BackendInfo,
capabilities: Capabilities,
own_client: u16,
/// The server's unique id.
server_uid: String,
/// Our unique id as the server knows it.
own_uid: Option<String>,
},
/// The server's channels and clients as they are now.
Presence(Box<Presence>),
OwnChannel(ChannelId),
Chat(ChatMessage),
Poke {
from: u16,
from_uid: Option<String>,
from_name: String,
message: String,
},
/// Incoming voice for the audio thread.
Audio(VoicePacket),
/// Who is talking (on, and off again when it stopped).
Talking {
client: u16,
talking: bool,
},
/// Our own stream's life, for the gateway directory.
OwnStream(OwnStreamEvent),
/// An Opus frame (48 kHz) of a watched stream, for the audio thread
/// ([`ConnectOptions::audio`]); `time` is its RTP time on the 48 kHz
/// clock.
StreamAudio {
stream: String,
time: u64,
data: Arc<[u8]>,
},
/// A watched stream ended: its audio leaves the mixer.
StreamAudioEnded(String),
/// A command failed (the connection stays).
Error(String),
/// The connection ended; the reason if it was not asked for. Sent once;
/// the stream task's closing reports may still follow (see the module
/// documentation).
Disconnected(Option<String>),
}
+265
View File
@@ -0,0 +1,265 @@
//! The registry of the engine's connectors, by address scheme.
//!
//! A session's voice source is a `voelin_proto::link::Session`
//! (`docs/session-seam.md` section 4.1). Which backend makes it is the
//! scheme of the address: [`Backends`] holds the plain connectors of
//! `voelin_proto::link::Connectors` (the Voelin protocol's QUIC connector
//! later, `FakeConnector` in tests) and the in-process connectors, which
//! also hand the engine what a `Session` has no room for yet (the TeamSpeak 6
//! stream task, [`StreamPort`]).
use std::sync::Arc;
use tokio::sync::mpsc;
use voelin_proto::link::{
AccountAgent, BoxFuture, ConnectParams, Connected, Connector, Connectors, HostIdentity,
HostTrust, SessionError,
};
use voelin_stream::PeerConfig;
use super::LinkCtx;
use crate::stream::{OwnStreamEvent, StreamCmd};
use crate::ts::TsConnector;
/// The scheme of the TeamSpeak servers a bookmark names without one.
pub(crate) const TEAMSPEAK_SCHEME: &str = "ts3server";
/// What comes back from the stream task of a connection that has one.
#[derive(Debug)]
pub(crate) enum StreamEvent {
/// Our own stream's life, for the gateway directory.
OwnStream(OwnStreamEvent),
/// An Opus frame of a watched stream, for the audio thread.
Audio { stream: String, time: u64, data: Arc<[u8]> },
/// A watched stream ended.
AudioEnded(String),
}
/// The in-process channel of TeamSpeak 6 streams past the `Session` trait
/// (`docs/session-seam.md` section 6.4): TeamSpeak 6 streams are peer to peer
/// and not v1 entities yet, so the commands go to the connection's stream
/// task and its events come back here.
pub(crate) struct StreamPort {
send: Box<dyn Fn(StreamCmd) + Send + Sync>,
/// What the stream task reports.
pub(crate) events: mpsc::UnboundedReceiver<StreamEvent>,
}
impl StreamPort {
/// A port whose commands go to `send`.
pub(crate) fn new(
send: impl Fn(StreamCmd) + Send + Sync + 'static,
events: mpsc::UnboundedReceiver<StreamEvent>,
) -> Self {
Self { send: Box::new(send), events }
}
/// Give the stream task a command.
pub(crate) fn send(&self, cmd: StreamCmd) {
(self.send)(cmd);
}
}
/// What an in-process backend needs besides the connect parameters.
#[derive(Clone)]
pub(crate) struct LocalCtx {
/// The session's side of the engine: its id, event bus, frames and
/// settings.
pub(crate) link: LinkCtx,
/// Open the audio devices (the stream task plays what streams carry).
pub(crate) audio: bool,
/// Network settings for stream peer connections.
pub(crate) stream_peer: PeerConfig,
}
impl LocalCtx {
pub(crate) fn new(link: LinkCtx, audio: bool, stream_peer: PeerConfig) -> Self {
Self { link, audio, stream_peer }
}
/// A context for a connection made outside an engine (a test or a tool
/// that calls a connector itself): a session of its own that nobody
/// listens to.
pub(crate) fn standalone() -> Self {
let (events, _) = tokio::sync::broadcast::channel(16);
let (frames, _) = tokio::sync::broadcast::channel(16);
let link = LinkCtx {
session: 0,
events,
frames,
settings: crate::settings::SharedSettings::new(crate::settings::Settings::in_memory()),
};
Self { link, audio: false, stream_peer: PeerConfig::default() }
}
}
/// A connection an in-process connector made.
pub(crate) struct LocalConnected {
pub(crate) connected: Connected,
/// The stream task's port, for a backend that runs one.
pub(crate) streams: Option<StreamPort>,
}
/// A connector that runs in this process and can use the engine's context
/// ([`LocalCtx`]); its sessions may come with a [`StreamPort`].
pub(crate) trait LocalConnector: Connector {
/// Whether this connector serves addresses of `scheme`. By default, the
/// schemes it names.
fn accepts(&self, scheme: &str) -> bool {
self.schemes().contains(&scheme)
}
/// Connect with the engine's context.
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>>;
}
/// The connectors of an engine, found by the scheme of an address.
///
/// A scheme served by an in-process connector goes to it, one served by a
/// plain connector ([`Backends::register`]) to that. An address without a
/// scheme is a TeamSpeak bookmark and is taken for a `ts3server` one.
#[derive(Clone)]
pub struct Backends {
connectors: Connectors,
locals: Vec<Arc<dyn LocalConnector>>,
account: Option<Arc<dyn AccountAgent>>,
/// The connections' trust in hosts that are neither valid nor pinned.
trust: Option<Arc<dyn HostTrust>>,
}
impl Default for Backends {
/// The engine's connectors: TeamSpeak 3 and 6 (`ts3server://` and
/// `teamspeak://`, and an address without a scheme).
fn default() -> Self {
let mut backends = Self::empty();
backends.register_teamspeak(TsConnector::new());
backends
}
}
impl Backends {
/// No connector at all. ([`Backends::default`] has the TeamSpeak one.)
pub fn empty() -> Self {
Self { connectors: Connectors::default(), locals: Vec::new(), account: None, trust: None }
}
/// Register a connector for the schemes it names.
pub fn register(&mut self, connector: Arc<dyn Connector>) {
self.connectors.register(connector);
}
pub(crate) fn register_local(&mut self, connector: Arc<dyn LocalConnector>) {
self.locals.push(connector);
}
/// Register the TeamSpeak connector for the schemes it names
/// (`ts3server`, `teamspeak`, and addresses without a scheme).
/// [`Backends::default`] registers one of its own; register yours to keep a
/// clone of it, whose [`TsConnector::set_myts_identity`] and
/// [`TsConnector::set_myts_data`] set the main myTeamSpeak account for every
/// connection it makes.
pub fn register_teamspeak(&mut self, connector: TsConnector) {
self.register_local(Arc::new(connector));
}
/// The device's Voelin account, which every connect hands the connector as
/// `ConnectParams::account`. No connector reads it yet: the TeamSpeak
/// connector takes the myTeamSpeak account it presents from its own setters
/// ([`TsConnector::set_myts_identity`], [`TsConnector::set_myts_data`]), and a
/// Voelin host's connector (the QUIC one, for its certificate) does not exist
/// yet. Follow-up H4 of `docs/session-seam.md` (11.2) moves the myTeamSpeak
/// proof from those setters to this hook. None is the default.
pub fn set_account(&mut self, agent: Option<Arc<dyn AccountAgent>>) {
self.account = agent;
}
/// The account agent, if one was set ([`Backends::set_account`]).
pub fn account(&self) -> Option<Arc<dyn AccountAgent>> {
self.account.clone()
}
/// Decide about hosts that are neither valid nor pinned. The default
/// refuses them: there is no trust dialog yet, and TeamSpeak has no host
/// key.
pub fn set_trust(&mut self, trust: Option<Arc<dyn HostTrust>>) {
self.trust = trust;
}
pub(crate) fn trust(&self) -> Arc<dyn HostTrust> {
self.trust.clone().unwrap_or_else(|| Arc::new(RefuseUnknownHosts))
}
/// The scheme of an address, lowercase; a TeamSpeak bookmark's when there
/// is none.
pub(crate) fn scheme(address: &str) -> String {
match address.split_once("://") {
Some((scheme, _)) => scheme.to_ascii_lowercase(),
None => TEAMSPEAK_SCHEME.to_owned(),
}
}
/// Open a session to `params.address` with the connector of its scheme.
pub(crate) fn connect(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
let scheme = Self::scheme(&params.address);
if let Some(local) = self.locals.iter().find(|c| c.accepts(&scheme)) {
return local.connect_local(params, ctx);
}
// Not `Connectors::connect`, which names the whole address when none serves it:
// the text is shown, and a TeamSpeak link carries a channel password.
let Some(connector) = self.connectors.for_address(&params.address) else {
let shown = without_query(&params.address).to_owned();
return Box::pin(async move {
Err(SessionError::Protocol(format!("no connector for {shown}")))
});
};
let connect = connector.connect(params);
Box::pin(async move {
let connected = connect.await?;
Ok(LocalConnected { connected, streams: None })
})
}
}
/// An address as it may be shown or logged: without its query and fragment,
/// where a link keeps a channel password or a host pin.
pub(crate) fn without_query(address: &str) -> &str {
address.split(['?', '#']).next().unwrap_or_default()
}
/// Refuses every host that asks to be trusted.
struct RefuseUnknownHosts;
impl HostTrust for RefuseUnknownHosts {
fn confirm(&self, _host: HostIdentity) -> BoxFuture<bool> {
Box::pin(async { false })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_bookmark_without_a_scheme_is_a_teamspeak_server() {
assert_eq!(Backends::scheme("ts.example.com:9987"), "ts3server");
assert_eq!(Backends::scheme("[::1]:9987"), "ts3server");
assert_eq!(Backends::scheme("TS3Server://ts.example.com"), "ts3server");
assert_eq!(Backends::scheme("teamspeak://x"), "teamspeak");
assert_eq!(Backends::scheme("voelin://host/i/code"), "voelin");
}
#[test]
fn an_address_is_shown_without_its_secrets() {
assert_eq!(without_query("ts3server://h?port=1&channelpassword=hunter2"), "ts3server://h");
assert_eq!(without_query("voelin://h/i/code#h=abcd"), "voelin://h/i/code");
assert_eq!(without_query("host:9987"), "host:9987");
}
}
+261
View File
@@ -0,0 +1,261 @@
//! What a session hands the connector of an address: the `ConnectParams` of
//! a [`VoiceOptions`] (`docs/session-seam.md` section 4.2).
//!
//! The options are the engine's own, and a connector reads them back: the
//! address is the link of the bookmark (a `ts3server://` link for a
//! bookmark that names a TeamSpeak server by `host[:port]`), the nickname,
//! the server password and the privilege key are in the hello, the identity
//! is the credential. What v1 has no field for yet (the channel to join and
//! its password, the client version a TeamSpeak server is shown) rides in
//! the address, as parameters of the link.
use std::sync::Arc;
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use bytes::Bytes;
use voelin_identity::{IdentityBlob, KIND_TEAMSPEAK};
use voelin_model::Link;
use voelin_proto::link::{ConnectParams, Credential, IssuerTrust, MediaSink, SessionError};
use voelin_proto::v1;
use super::{Backends, VoiceOptions, without_query};
/// The link parameter that carries the client version to impersonate: the
/// user's spec (`VoiceOptions::client_version`), in unpadded URL-safe base64.
/// The connector for TeamSpeak resolves it; other connectors never read it.
pub(crate) const VERSION_PARAM: &str = "client_version";
/// The connect parameters of a connection, from the options the session was
/// asked to connect with.
///
/// The address is the link of the bookmark (the channel and its password
/// ride in it, and so does the client version to claim, until v1 has fields
/// for them), the server password is `Hello.password` and the privilege key
/// `Hello.invite_code`. The identity goes as the credential of its kind; no
/// account is used yet.
///
/// An address a link cannot carry is refused here ([`bookmark`]), and so is
/// an identity that is of no kind a connector can use.
pub(crate) fn connect_params(
options: &VoiceOptions,
media: Arc<dyn MediaSink>,
backends: &Backends,
) -> Result<ConnectParams, SessionError> {
let hello = v1::Hello {
version: 1,
client: Some(v1::ClientInfo {
name: "Voelin".into(),
version: voelin_platform::crash::app_version().to_owned(),
platform: std::env::consts::OS.into(),
kind: v1::ClientKind::User as i32,
}),
nickname: options.nickname.clone(),
password: options.server_password.clone().unwrap_or_default(),
invite_code: options.token.clone().unwrap_or_default(),
..Default::default()
};
Ok(ConnectParams {
address: address_link(options)?,
credential: credential(options.identity.as_ref())?,
linked: Vec::new(),
account: backends.account(),
issuer_trust: IssuerTrust::Unknown,
hello,
host_pin: None,
trust: backends.trust(),
media,
push_capacity: 1024,
timeout: Duration::from_secs(35),
})
}
/// The credential of an identity (`docs/session-seam.md` section 7). A
/// TeamSpeak identity goes as the JSON the key store keeps, and none at all as
/// an empty one, for which the TeamSpeak connector makes an identity up (the
/// protocol's convention for "generate one", follow-up P11); a Voelin key
/// signs. A TeamSpeak identity that holds no JSON is refused: sent as it is,
/// it would be that same empty blob and be taken for the request to make one
/// up, which only the absence of an identity may be.
fn credential(identity: Option<&IdentityBlob>) -> Result<Credential, SessionError> {
let Some(blob) = identity else {
return Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: Bytes::new() });
};
if blob.is_teamspeak() {
if blob.json.trim().is_empty() {
return Err(SessionError::Protocol(
"the TeamSpeak identity cannot be read: it is empty".into(),
));
}
let json = Bytes::copy_from_slice(blob.json.as_bytes());
Ok(Credential::Foreign { kind: KIND_TEAMSPEAK, blob: json })
} else if blob.is_voelin() {
let key = blob.voelin_key().map_err(|e| {
SessionError::Protocol(format!("the Voelin identity cannot be read: {e}"))
})?;
Ok(Credential::Voelin(Arc::new(key)))
} else {
Err(SessionError::Protocol(format!(
"an identity of kind {:?} cannot be used to connect",
blob.kind
)))
}
}
/// The `ts3server://` link of the options' address, with the channel to join
/// and the client version to claim.
fn address_link(options: &VoiceOptions) -> Result<String, SessionError> {
let mut link = match Link::parse(&options.address) {
Some(Link::Server(link)) => link,
// Not a TeamSpeak link, or none: a bookmark's `host[:port]`.
_ if !options.address.contains("://") => bookmark(&options.address)?,
// Some other scheme: as given, for the connector of that scheme.
_ => return Ok(options.address.clone()),
};
link.channel = options.channel.clone().filter(|c| !c.is_empty()).or(link.channel);
link.channel_password =
options.channel_password.clone().filter(|p| !p.is_empty()).or(link.channel_password);
let mut url = link.to_url();
if let Some(spec) = &options.client_version {
url.push(if url.contains('?') { '&' } else { '?' });
url.push_str(VERSION_PARAM);
url.push('=');
url.push_str(&URL_SAFE_NO_PAD.encode(spec));
}
Ok(url)
}
/// The link to a bookmark's `host[:port]`.
///
/// A link cannot say everything an address can: it drops a port that is no
/// port (`ServerLink::new` takes `host:99999` for the host `host` and joins
/// the default port), and it ends the host at a `?`, `#` or `/` and decodes a
/// `%` (so that a `?` in the host would hide the channel behind the next
/// one). The TeamSpeak library refuses such an address when it resolves it;
/// so does this, in words, instead of connecting to something else.
fn bookmark(address: &str) -> Result<voelin_model::ServerLink, SessionError> {
let address = address.trim();
// Without the query: a link keeps secrets in it.
let shown = without_query(address);
let not_an_address = || SessionError::Protocol(format!("not a server address: {shown}"));
if address.is_empty()
|| address
.chars()
.any(|c| matches!(c, '?' | '#' | '/' | '%') || c.is_whitespace() || c.is_control())
{
return Err(not_an_address());
}
// The text after the port's colon: `[v6]:port`, or `host:port` with the one
// colon (more colons are an IPv6 address without a port).
let port = if let Some(rest) = address.strip_prefix('[') {
let (_, after) = rest.split_once(']').ok_or_else(not_an_address)?;
(!after.is_empty()).then(|| after.strip_prefix(':').unwrap_or(after))
} else {
address.rsplit_once(':').filter(|(host, _)| !host.contains(':')).map(|(_, port)| port)
};
if let Some(port) = port
&& !port.parse::<u16>().is_ok_and(|port| port != 0)
{
return Err(SessionError::Protocol(format!(
"the port in {shown} is not a number from 1 to 65535"
)));
}
Ok(voelin_model::ServerLink::new(address))
}
#[cfg(test)]
mod tests {
use super::*;
use voelin_identity::IdentityKey;
fn params(options: &VoiceOptions) -> Result<ConnectParams, SessionError> {
let (media, _rx) = voelin_proto::test_util::media_channel();
connect_params(options, media, &Backends::empty())
}
/// The identity of the options is the credential of its kind: a TeamSpeak
/// identity as the JSON the key store keeps, none as the empty blob a
/// connector makes an identity up for, a Voelin key as its signer.
#[test]
fn an_identity_is_the_credential_of_its_kind() {
let mut options = VoiceOptions::new("ts.example.com", "nick");
let none = params(&options).unwrap();
assert!(matches!(
&none.credential,
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
));
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, r#"{"key":"k"}"#));
let sent = params(&options).unwrap();
assert!(matches!(
&sent.credential,
Credential::Foreign { kind: "teamspeak", blob } if &blob[..] == br#"{"key":"k"}"#
));
let key = IdentityKey::generate().unwrap();
options.identity = Some(IdentityBlob::voelin(&key).unwrap());
let Credential::Voelin(signer) = params(&options).unwrap().credential else {
panic!("a Voelin credential")
};
assert_eq!(signer.public_key(), key.public_key());
assert_eq!(signer.sign(b"hello"), key.sign(b"hello"));
// A Voelin blob whose key cannot be read, and a kind that connects to
// nothing: refused in words, without the JSON.
options.identity = Some(IdentityBlob::new("voelin", "x", 0, "hunter2"));
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
assert!(
text.starts_with("the Voelin identity cannot be read") && !text.contains("hunter2")
);
options.identity = Some(IdentityBlob::new("account", "x", 0, "hunter2"));
let Err(SessionError::Protocol(text)) = params(&options) else { panic!("a refusal") };
assert_eq!(text, "an identity of kind \"account\" cannot be used to connect");
}
/// A TeamSpeak identity with no JSON is no identity. The empty blob is
/// what asks the TeamSpeak connector to make one up (`identity: None`), so
/// it is refused here instead of being sent as that request.
#[test]
fn a_teamspeak_identity_without_json_is_refused() {
let mut options = VoiceOptions::new("ts.example.com", "nick");
for json in ["", " \n\t"] {
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json));
let Err(SessionError::Protocol(text)) = params(&options) else {
panic!("a refusal for {json:?}")
};
assert_eq!(text, "the TeamSpeak identity cannot be read: it is empty");
}
// No identity at all is the request to make one up, as before.
options.identity = None;
assert!(matches!(
params(&options).unwrap().credential,
Credential::Foreign { kind: "teamspeak", blob } if blob.is_empty()
));
}
/// The client version spec rides the link as it was typed, whatever it
/// holds, and only for an address that is a TeamSpeak bookmark or link.
#[test]
fn the_client_version_spec_rides_the_link_unchanged() {
let spec = |address: &str, spec: &str| {
let mut options = VoiceOptions::new(address, "nick");
options.client_version = Some(spec.into());
params(&options).unwrap().address
};
let address = spec("ts.example.com:9988", "windows@3.6.2 [Build: 1]&x=#");
let (_, query) = address.split_once('?').unwrap();
let text = query
.split('&')
.find_map(|pair| pair.strip_prefix("client_version="))
.expect("the parameter");
let decoded = URL_SAFE_NO_PAD.decode(text).unwrap();
assert_eq!(decoded, b"windows@3.6.2 [Build: 1]&x=#");
// Another scheme is left as it is: its connector has no use for a TeamSpeak
// client's version.
assert_eq!(spec("voelin://host/i/code", "generic"), "voelin://host/i/code");
// No spec, no parameter.
let options = VoiceOptions::new("ts.example.com", "nick");
assert!(!params(&options).unwrap().address.contains(VERSION_PARAM));
}
}
@@ -0,0 +1,363 @@
//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each
//! connection the test asks for to the test, which plays the server by
//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session
//! gives. These are the tests that need the inner link itself:
//!
//! - the stream commands, which travel on the in-process port of the link
//! and which a `voelin_proto::link::Session` has no part in until the
//! stream task moves (`docs/session-seam.md` sections 6.4 and 9.2);
//! - the order in which a reconnect shuts the streams and the old connection
//! down, which is the order of the one queue `LinkSession` keeps;
//! - a link that keeps talking after the engine replaced its connection,
//! which a closed `FakeSession` cannot do on purpose.
//!
//! (They were integration tests while the inner link was public; it is the
//! TeamSpeak module's now, and so are these.)
//!
//! Presence, chat, the dedup of a message that comes twice, history, transfers
//! and the rest of what the engine does with a session are tested on the
//! protocol repository's fake host in `tests/session_fake.rs`. Nothing here
//! needs a TeamSpeak server or a TeamSpeak type.
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::{broadcast, mpsc};
use super::{Backends, LinkCmd, LinkCtx, LinkEvent};
use crate::settings::Settings;
use crate::stream::{StreamCmd, StreamSetup};
use crate::ts::ts_session::LinkConnector;
use crate::ts::{ConnectOptions, ServerLink};
use crate::{
BackendInfo, Command, Engine, Event, History, SessionId, SessionState, VoiceOptions, VoiceState,
};
use voelin_model::{
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
ServerDetails,
};
/// A connection the session asked the link for.
struct Conn {
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
}
impl Conn {
/// Play `script`, the server's side, in order.
fn play(&self, script: impl IntoIterator<Item = LinkEvent>) {
for event in script {
self.events.send(event).expect("the session listens");
}
}
/// The next command the session gave.
async fn cmd(&mut self) -> LinkCmd {
tokio::time::timeout(Duration::from_secs(10), self.cmds.recv())
.await
.expect("a command in time")
.expect("the session keeps the connection")
}
}
/// Hands every connection to the test.
struct FakeLink {
conns: mpsc::UnboundedSender<Conn>,
}
impl FakeLink {
fn new() -> (Self, mpsc::UnboundedReceiver<Conn>) {
let (conns, rx) = mpsc::unbounded_channel();
(Self { conns }, rx)
}
}
impl ServerLink for FakeLink {
fn spawn(
&self,
_options: ConnectOptions,
_ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
let _ = self.conns.send(Conn { cmds, events });
}
}
const SESSION: SessionId = 1;
const SERVER_UID: &str = "fake-server=";
const ME: u16 = 7;
const ME_UID: &str = "me=";
const LOBBY: ChannelId = 1;
const GAMES: ChannelId = 2;
struct Harness {
engine: Engine,
events: broadcast::Receiver<Event>,
conns: mpsc::UnboundedReceiver<Conn>,
}
impl Harness {
fn start() -> Self {
let (link, conns) = FakeLink::new();
let mut backends = Backends::empty();
backends.register_local(Arc::new(LinkConnector::any(Arc::new(link))));
let engine =
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
let events = engine.subscribe();
Self { engine, events, conns }
}
/// Ask for a voice connection and take it from the link.
async fn connect(&mut self) -> Conn {
let options = VoiceOptions::new("fake.test:9987", "tester");
self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
tokio::time::timeout(Duration::from_secs(10), self.conns.recv())
.await
.expect("the session spawns the link")
.expect("the link lives")
}
/// The next event `f` picks, skipping the others.
async fn next<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> T {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
if let Some(t) = f(self.events.recv().await.expect("engine events")) {
return t;
}
}
})
.await
.expect("event in time")
}
/// The next state of the session that `ok` accepts.
async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState {
self.next(|e| match e {
Event::State { state, .. } if ok(&state) => Some(state),
_ => None,
})
.await
}
/// The next live chat message.
async fn chat(&mut self) -> ChatMessage {
self.next(|e| match e {
Event::Chat { message, .. } => Some(message),
_ => None,
})
.await
}
}
fn now_ms() -> i64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64
}
fn capabilities(streams: bool) -> Capabilities {
Capabilities { streams, file_transfer: true, ..Default::default() }
}
fn backend() -> BackendInfo {
BackendInfo { product: "Fake".into(), version: "1.2".into() }
}
fn connected(streams: bool) -> LinkEvent {
LinkEvent::Connected {
name: "Fake Server".into(),
backend: backend(),
capabilities: capabilities(streams),
own_client: ME,
server_uid: SERVER_UID.into(),
own_uid: Some(ME_UID.into()),
}
}
/// A client as a TeamSpeak link reports one: with its database id, and not
/// talking (who talks comes from the media, which the session derives).
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
ClientInfo {
id,
uid: Some(format!("{nickname}=")),
nickname: nickname.into(),
channel,
talking: Some(false),
database_id: Some(1_000 + u64::from(id)),
..Default::default()
}
}
/// Two channels, three clients; we are in the second channel. The shape is
/// what a TeamSpeak link reports: sibling channels form an order chain, the
/// server is named and has its unique id.
fn presence() -> Presence {
let channel =
|id, name: &str, order| ChannelInfo { id, name: name.into(), order, ..Default::default() };
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
presence.server = ServerDetails {
name: "Fake Server".into(),
uid: Some(SERVER_UID.into()),
version: backend().version,
..Default::default()
};
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby", 0));
presence.channels.insert(GAMES, channel(GAMES, "Games", LOBBY));
let me = ClientInfo { uid: Some(ME_UID.into()), ..client(ME, "tester", GAMES) };
for c in [me, client(8, "alice", GAMES), client(9, "bob", LOBBY)] {
presence.clients.insert(c.id, c);
}
presence
}
fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage {
ChatMessage {
target: ChatTarget::Channel(GAMES),
author_name: author.into(),
author_uid: Some(format!("{author}=")),
author_id: None,
text: text.into(),
ts_ms,
via_relay: false,
blocked: false,
}
}
/// Stream commands reach a link that has streams in its capabilities, and
/// end with the connection; a link without them is spared. (The rest of what
/// the user asks for is checked on the fake host in `session_fake.rs`.)
#[tokio::test(flavor = "multi_thread")]
async fn stream_commands_reach_a_link_with_streams() {
let mut h = Harness::start();
let mut conn = h.connect().await;
conn.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
// No streams in the capabilities: the session refuses them itself.
let engine = h.engine.clone();
let setup = || StreamSetup { name: "screen".into(), ..Default::default() };
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
let error = h
.next(|e| match e {
Event::Error { message, .. } => Some(message),
_ => None,
})
.await;
assert!(error.contains("streams"), "{error}");
assert!(conn.cmds.try_recv().is_err(), "nothing reached the link");
// A link with streams: stream commands go to it, and end with the connection.
let mut with_streams = {
let link_engine = h.engine.clone();
link_engine.send(Command::ConnectVoice {
session: SESSION,
options: Box::new(VoiceOptions::new("fake.test:9987", "tester")),
});
h.conns.recv().await.expect("the second connection")
};
// The replaced connection is told to go.
assert!(matches!(conn.cmd().await, LinkCmd::Disconnect));
with_streams.play([connected(true)]);
h.next(|e| match e {
Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()),
_ => None,
})
.await;
// A connection with streams is given the (empty) stream directory first.
let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else {
panic!("the stream directory")
};
assert!(directory.is_empty());
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else {
panic!("a stream start")
};
assert_eq!((setup.name.as_str(), auto_accept), ("screen", true));
engine.send(Command::StopStream { session: SESSION });
assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop)));
engine.send(Command::DisconnectVoice { session: SESSION });
assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect));
}
/// A reconnect ends the streams of the connection it replaces through that
/// connection, before the connection itself: the old link is given
/// `StreamCmd::Shutdown` and only then `Disconnect`. A link that ends its
/// connection on `Disconnect` (the TeamSpeak one stops reading commands
/// there) relies on this order for the streams to hear of their end.
#[tokio::test(flavor = "multi_thread")]
async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() {
let mut h = Harness::start();
let mut old = h.connect().await;
old.play([
connected(true),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
let LinkCmd::Stream(StreamCmd::Directory(directory)) = old.cmd().await else {
panic!("the stream directory")
};
assert!(directory.is_empty());
// Connecting again replaces the connection.
let _new = h.connect().await;
let LinkCmd::Stream(StreamCmd::Shutdown(reason)) = old.cmd().await else {
panic!("the streams end first")
};
assert_eq!(reason, "voice reconnecting");
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
}
/// Events of a connection the session replaced do not reach it.
#[tokio::test(flavor = "multi_thread")]
async fn a_replaced_connection_is_ignored() {
let mut h = Harness::start();
let mut old = h.connect().await;
old.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
let new = h.connect().await;
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
// The old connection winds down, and says more than it should.
let mut stale = presence();
stale.clients.insert(10, client(10, "ghost", LOBBY));
old.play([
LinkEvent::Presence(Box::new(stale)),
LinkEvent::Chat(message("ghost", "boo", now_ms())),
LinkEvent::Disconnected(None),
]);
let mut fresh = presence();
fresh.clients.remove(&9);
// A link that says we are in the lobby shows us in the lobby.
fresh.clients.get_mut(&ME).expect("we are on the server").channel = LOBBY;
new.play([
connected(false),
LinkEvent::Presence(Box::new(fresh.clone())),
LinkEvent::OwnChannel(LOBBY),
]);
// Only the new connection's presence is shown (nobody else has 2 clients).
let shown = h
.next(|e| match e {
Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => {
Some(presence)
}
_ => None,
})
.await;
assert_eq!(*shown, fresh);
let state = h.state(|s| s.own_channel == Some(LOBBY)).await;
assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count");
// Channel chat reaches the channel we are in (the lobby, now).
new.play([LinkEvent::Chat(ChatMessage {
target: ChatTarget::Channel(LOBBY),
..message("alice", "hello", now_ms())
})]);
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
}
+322
View File
@@ -0,0 +1,322 @@
//! The engine's side of the seam against the protocol repository's fake host
//! (`docs/session-seam.md` sections 9.2 and 16): the voice path through a
//! `SessionLink` that talks to a `FakeSession`, and the link conformance
//! suite run against the session the engine's registry hands over.
//!
//! The tests that need only the engine's public API are in
//! `tests/session_fake.rs`; these need what is private to the crate: the
//! `LinkCmd`/`LinkEvent` vocabulary between `session.rs` and `SessionLink`,
//! the registry's `connect` and the context of a connector called outside an
//! engine.
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
use voelin_proto::link::{FlowId, MediaClass, MediaPacket, voice_sub};
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
use voelin_proto::media::{RtpHeader, RtpView};
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
use voelin_proto::test_util::{
FAKE_HOST_UID, FakeConnector, FakeHandle, connect_params, eventually,
};
use voelin_proto::v1::{self, entity::Kind};
use super::*;
const WAIT: Duration = Duration::from_secs(10);
/// An Opus frame of 20 ms, mono (TOC `0xf8`), and the same as stereo (`0xfc`).
const MONO: [u8; 3] = [0xf8, 0xff, 0xfe];
const STEREO: [u8; 3] = [0xfc, 0xff, 0xfe];
const ALICE: u32 = 50;
const ALICE_SLOT: u32 = 90;
const BOB: u32 = 51;
const BOB_SLOT: u32 = 91;
fn put(connector: &FakeConnector, kind: Kind) {
connector.host().put(v1::Entity { kind: Some(kind) }).expect("the fake host stores it");
}
/// A host with one server, a lobby, and alice and bob talking in it.
fn host() -> FakeConnector {
let connector = FakeConnector::new();
put(
&connector,
Kind::Server(v1::Server {
id: 1,
name: "Fake Host".into(),
uid: "fake-host".into(),
default_channel_id: 10,
..Default::default()
}),
);
put(
&connector,
Kind::Channel(v1::Channel {
id: 10,
server_id: 1,
kind: v1::ChannelKind::Voice as i32,
name: "Lobby".into(),
..Default::default()
}),
);
for (user, participant, slot, name) in
[(2, ALICE, ALICE_SLOT, "alice"), (3, BOB, BOB_SLOT, "bob")]
{
put(
&connector,
Kind::User(v1::User {
id: user,
uid: vec![user as u8; 32].into(),
uid_kind: v1::IdKind::Voelin as i32,
name: name.into(),
..Default::default()
}),
);
put(
&connector,
Kind::Voice(v1::VoiceState {
server_id: 1,
participant_id: participant,
user_id: user,
channel_id: 10,
slot,
nick: name.into(),
..Default::default()
}),
);
}
connector
}
/// A `SessionLink` over a fake host, driven the way `session.rs` drives it.
struct HostRig {
handle: FakeHandle,
cmds: mpsc::UnboundedSender<LinkCmd>,
events: mpsc::UnboundedReceiver<LinkEvent>,
/// Our participant and voice slot, as the host gave them.
own_client: u16,
own_slot: u32,
/// The clients the link told started talking, in order.
talking: Vec<u16>,
}
/// The next event `f` picks from `events`, skipping the others.
async fn event_of<T>(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
mut f: impl FnMut(LinkEvent) -> Option<T>,
) -> T {
tokio::time::timeout(WAIT, async {
loop {
if let Some(t) = f(events.recv().await.expect("the link lives")) {
return t;
}
}
})
.await
.expect("an event in time")
}
impl HostRig {
async fn connect() -> Self {
let connector = host();
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let link = SessionLink::new(backends);
let (cmds, cmd_rx) = mpsc::unbounded_channel();
let (event_tx, mut events) = mpsc::unbounded_channel();
let ctx = LocalCtx::standalone().link;
link.spawn(VoiceOptions::new("fake://host", "tester"), ctx, cmd_rx, event_tx);
let own_client = event_of(&mut events, |e| match e {
LinkEvent::Connected { own_client, .. } => Some(own_client),
_ => None,
})
.await;
event_of(&mut events, |e| matches!(e, LinkEvent::OwnChannel(10)).then_some(())).await;
let own_slot = connector
.host()
.entities(&v1::Scope { kind: v1::ScopeKind::Live as i32, id: 1 })
.into_iter()
.find_map(|e| match e.kind? {
Kind::Voice(v) if v.participant_id == u32::from(own_client) => Some(v.slot),
_ => None,
})
.expect("the host seated us in voice");
let handle = connector.last_session().expect("the connector made a session");
Self { handle, cmds, events, own_client, own_slot, talking: Vec::new() }
}
/// The next voice packet the audio thread would get; who started to talk on
/// the way is kept in `talking`.
async fn audio(&mut self) -> VoicePacket {
let talking = &mut self.talking;
event_of(&mut self.events, |e| match e {
LinkEvent::Talking { client, talking: true } => {
talking.push(client);
None
}
LinkEvent::Audio(packet) => Some(packet),
_ => None,
})
.await
}
fn give(&self, cmd: LinkCmd) {
self.cmds.send(cmd).expect("the link listens");
}
}
/// A voice packet of `slot` on sub-flow `sub`, as a host delivers it.
fn voice_packet(slot: u32, sub: u8, sequence: u16, payload: &[u8]) -> MediaPacket {
let flow = FlowId::new(slot, sub);
let mut out = bytes::BytesMut::new();
RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960)
.write(flow, &mut out)
.expect("a header");
out.extend_from_slice(payload);
MediaPacket { flow, rtp: out.freeze() }
}
fn voice(payload: &[u8]) -> EncodedVoice {
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
}
/// Our voice leaves as RTP on the slot the host gave us: the sequence counts
/// every packet, the timestamp advances by the duration of the previous one,
/// the marker is on the first packet of a spurt, the end of a spurt is an
/// empty payload sent once, and the SSRC is the flow (protocol section 6).
#[tokio::test(flavor = "multi_thread")]
async fn our_voice_is_rtp_on_the_slot_the_host_gave_us() {
let rig = HostRig::connect().await;
// The fake host loops accepted media back; this test looks at what left.
rig.handle.set_loopback(false);
for n in 1..=3 {
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, n])));
}
rig.give(LinkCmd::Audio(voice(&[])));
rig.give(LinkCmd::Audio(voice(&[0xf8, 0xff, 0xfe, 9])));
let handle = rig.handle.clone();
eventually(WAIT, "the five packets", || handle.sent_media().len() == 5).await;
let flow = FlowId::new(rig.own_slot, voice_sub::CHANNEL);
let sent = rig.handle.sent_media();
let seen: Vec<_> = sent
.iter()
.map(|(class, packet)| {
let view = RtpView::parse(&packet.rtp).expect("RTP");
assert_eq!(*class, MediaClass::Voice);
assert_eq!(packet.flow, flow);
assert_eq!((view.payload_type(), view.ssrc()), (PT_OPUS, flow.0));
(view.sequence(), view.marker(), view.timestamp(), view.payload().to_vec())
})
.collect();
let ticks = OPUS_20_MS_TICKS;
assert_eq!(
seen,
[
(0, true, 0, vec![0xf8, 0xff, 0xfe, 1]),
(1, false, ticks, vec![0xf8, 0xff, 0xfe, 2]),
(2, false, 2 * ticks, vec![0xf8, 0xff, 0xfe, 3]),
// The end of the spurt: no payload, no marker, once.
(3, false, 3 * ticks, vec![]),
// The next spurt marks its first packet again.
(4, true, 3 * ticks, vec![0xf8, 0xff, 0xfe, 9]),
]
);
}
/// The RTP of other slots becomes the packets of the audio thread: the talker
/// is the participant of the slot, a whisper sub-flow is a whisper, a stereo
/// Opus frame is music, an empty payload ends the spurt; what is no voice of a
/// slot the host told about is dropped.
#[tokio::test(flavor = "multi_thread")]
async fn the_voice_of_other_slots_reaches_the_audio_thread() {
let mut rig = HostRig::connect().await;
let handle = rig.handle.clone();
// A slot nobody has, a probe and feedback: nothing. Then alice, mono.
handle.inject_media(voice_packet(777, voice_sub::CHANNEL, 1, &MONO));
handle.inject_media(MediaPacket { flow: FlowId::PROBE, rtp: bytes::Bytes::from_static(&[1]) });
handle.inject_media(MediaPacket {
flow: FlowId::FEEDBACK,
rtp: bytes::Bytes::from_static(&[1, 2]),
});
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 5, &MONO));
let packet = rig.audio().await;
assert_eq!(
(packet.talker.0, packet.seq, packet.codec, packet.whisper, packet.payload.as_slice()),
(ALICE as u16, 5, VoiceCodec::Voice, false, MONO.as_slice())
);
// Bob whispers (sub-flow 1) in stereo: music, a whisper.
handle.inject_media(voice_packet(BOB_SLOT, 1, 6, &STEREO));
let packet = rig.audio().await;
assert_eq!(
(packet.talker.0, packet.seq, packet.codec, packet.whisper),
(BOB as u16, 6, VoiceCodec::Music, true)
);
// Alice stops: an empty payload.
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 7, &[]));
let packet = rig.audio().await;
assert_eq!((packet.talker.0, packet.seq, packet.payload.len()), (ALICE as u16, 7, 0));
// Who talks comes from the same packets: alice started, then bob, once each
// (the slot nobody has started nobody).
assert_eq!(rig.talking, [ALICE as u16, BOB as u16]);
}
/// A host whose session loops our own voice back (the fake one does, so that
/// the conformance suite can see media move) does not make the engine play us
/// our own voice or show us as talking: the engine never plays itself.
#[tokio::test(flavor = "multi_thread")]
async fn our_own_voice_coming_back_is_not_played_back() {
let mut rig = HostRig::connect().await;
// The fake host loops accepted media back into the sink (the default).
rig.give(LinkCmd::Audio(voice(&MONO)));
let handle = rig.handle.clone();
eventually(WAIT, "the packet to leave", || handle.sent_media().len() == 1).await;
// A packet of alice behind it: when this one is out, ours has been through.
handle.inject_media(voice_packet(ALICE_SLOT, voice_sub::CHANNEL, 1, &MONO));
let own = rig.own_client;
let mut heard = Vec::new();
while heard.last().is_none_or(|talker| *talker != ALICE as u16) {
heard.push(rig.audio().await.talker.0);
}
assert!(!heard.contains(&own), "the engine played our own voice back: {heard:?}");
}
/// The link conformance suite of the protocol repository against the session
/// the engine's registry hands over: the registry adds nothing to a plain
/// connector's session (`Backends::connect` returns it untouched), so the 17
/// cases pass as they do in the protocol repository, none skipped.
#[tokio::test(flavor = "multi_thread")]
async fn the_conformance_suite_passes_on_a_session_of_the_registry() {
async fn through_the_registry() -> Fixture {
let connector = FakeConnector::new();
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let (params, media) = connect_params("fake://conformance");
let local = backends
.connect(params, LocalCtx::standalone())
.await
.unwrap_or_else(|e| panic!("the registry connects: {e}"));
assert_eq!(local.connected.host_uid, FAKE_HOST_UID, "the connector's own answer");
assert!(local.streams.is_none(), "a plain connector has no stream port");
let backend = connector.last_session().expect("the connector made a session");
// The session is the connector's own, so a request id means the same to both.
Fixture {
shared_request_ids: true,
..Fixture::new(local.connected.session, local.connected.pushes, media, backend)
}
}
let report = conformance::run(&through_the_registry).await;
assert_eq!(report.cases.len(), conformance::CASES.len());
assert_eq!(report.cases.len(), 17, "the suite of c5bb6b9 has 17 cases");
assert!(
report.cases.iter().all(|(_, verdict)| *verdict == Verdict::Passed),
"{:?}",
report.cases
);
}
+310
View File
@@ -0,0 +1,310 @@
//! Voice across the seam, engine side (`docs/session-seam.md` section 6.1):
//! our encoded frames as RTP on our voice slot, the RTP of other slots as
//! the audio thread's packets, and who is talking from the media.
//!
//! `voelin-audio`'s [`EncodedVoice`] and [`VoicePacket`] stay what the audio
//! thread speaks; this is the framing in the v1 media codec
//! (`voelin_proto::media`, protocol section 6).
use std::collections::{HashMap, HashSet};
use std::time::{Duration, Instant};
use bytes::BytesMut;
use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
use voelin_proto::media::opus::{self, Toc};
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, PT_OPUS};
use voelin_proto::media::{RtpHeader, RtpView};
/// A talker is silent after this long without a packet.
pub(crate) const TALK_SILENCE: Duration = Duration::from_millis(400);
/// Our voice as RTP: the sequence number counts every packet from 0, the
/// timestamp starts at 0 and advances by the duration of the previous
/// packet, the marker is set on the first packet of a spurt, and the end of a
/// spurt is a packet with an empty payload, sent once.
#[derive(Default)]
pub(crate) struct Uplink {
sequence: u16,
timestamp: u32,
/// The ticks the last voice packet spans.
ticks: u32,
in_spurt: bool,
}
impl Uplink {
/// `voice` as the RTP packet of our voice slot.
pub(crate) fn frame(&mut self, slot: u32, voice: &EncodedVoice) -> Option<MediaPacket> {
let flow = FlowId::new(slot, voice_sub::CHANNEL);
// The previous packet's duration has passed.
self.timestamp = self.timestamp.wrapping_add(self.ticks);
let end = voice.is_end();
let mut header = RtpHeader::new(PT_OPUS, self.sequence, self.timestamp);
header.marker = !end && !self.in_spurt;
self.ticks =
if end { 0 } else { opus::packet_ticks(&voice.payload).unwrap_or(OPUS_20_MS_TICKS) };
self.in_spurt = !end;
self.sequence = self.sequence.wrapping_add(1);
let mut out = BytesMut::with_capacity(header.encoded_len() + voice.payload.len());
header.write(flow, &mut out).ok()?;
out.extend_from_slice(&voice.payload);
Some(MediaPacket { flow, rtp: out.freeze() })
}
}
/// A voice packet of some slot, taken from its RTP.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Incoming {
pub(crate) slot: u32,
/// Sent on a whisper sub-flow (1 to 6).
pub(crate) whisper: bool,
pub(crate) sequence: u16,
pub(crate) codec: VoiceCodec,
/// Empty: the spurt ends.
pub(crate) payload: Vec<u8>,
}
impl Incoming {
/// Parse a media packet. `None` for what is not the voice of a slot:
/// feedback, probes, a flow that is no media, a packet that is no RTP.
pub(crate) fn parse(packet: &MediaPacket) -> Option<Incoming> {
if !packet.flow.is_media() {
return None;
}
let view = RtpView::parse(&packet.rtp).ok()?;
let payload = view.payload();
// Stereo Opus is music; the jitter buffer decodes both the same way.
let codec = match Toc::parse(payload) {
Ok(toc) if toc.stereo() => VoiceCodec::Music,
_ => VoiceCodec::Voice,
};
Some(Incoming {
slot: packet.flow.slot(),
whisper: (voice_sub::FIRST_TALK_TARGET..=voice_sub::LAST_TALK_TARGET)
.contains(&packet.flow.sub()),
sequence: view.sequence(),
codec,
payload: payload.to_vec(),
})
}
/// The packet for the audio thread, from `talker`.
pub(crate) fn voice(self, talker: u16) -> VoicePacket {
VoicePacket {
talker: TalkerId(talker),
seq: self.sequence,
codec: self.codec,
whisper: self.whisper,
payload: self.payload,
}
}
}
/// Who is talking: derived from the media (protocol section 6.4). A talker
/// starts with its first packet and stops after [`TALK_SILENCE`] without one.
///
/// A host can also say that someone talks whose voice it does not carry as
/// media (a `Speaking` signal; TeamSpeak's Speex and CELT talkers are such):
/// that is a hint, which holds until the host says it is over.
#[derive(Default)]
pub(crate) struct TalkTracker {
last: HashMap<u16, Instant>,
hinted: HashSet<u16>,
}
impl TalkTracker {
/// A packet of `client` arrived; whether this starts its talking.
pub(crate) fn heard(&mut self, client: u16, now: Instant) -> bool {
let was = self.is_talking(client);
self.last.insert(client, now);
!was
}
/// The host says `client` talks or has stopped; whether this changes
/// whether it is talking.
pub(crate) fn hint(&mut self, client: u16, talking: bool) -> bool {
let was = self.is_talking(client);
if talking {
self.hinted.insert(client);
} else {
self.hinted.remove(&client);
}
was != self.is_talking(client)
}
/// Forget the hints about clients `present` does not hold any more: a
/// client that left cannot say it stopped.
pub(crate) fn retain_hints(&mut self, present: impl Fn(u16) -> bool) {
self.hinted.retain(|client| present(*client));
}
/// The talkers that have been silent long enough, no longer talking.
pub(crate) fn expire(&mut self, now: Instant) -> Vec<u16> {
let mut silent: Vec<u16> = self
.last
.iter()
.filter(|(_, last)| now.saturating_duration_since(**last) >= TALK_SILENCE)
.map(|(client, _)| *client)
.collect();
silent.sort_unstable();
for client in &silent {
self.last.remove(client);
}
silent.retain(|client| !self.hinted.contains(client));
silent
}
pub(crate) fn is_talking(&self, client: u16) -> bool {
self.last.contains_key(&client) || self.hinted.contains(&client)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// 20 ms of CELT, mono, one frame.
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
fn voice(payload: &[u8]) -> EncodedVoice {
EncodedVoice { codec: VoiceCodec::Voice, payload: payload.to_vec() }
}
fn view(packet: &MediaPacket) -> RtpView<'_> {
RtpView::parse(&packet.rtp).unwrap()
}
#[test]
fn our_voice_is_sequenced_stamped_and_marked() {
let mut up = Uplink::default();
let first = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
let second = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
assert_eq!((first.flow.slot(), first.flow.sub()), (8, 0));
let (a, b) = (view(&first), view(&second));
assert_eq!((a.sequence(), a.timestamp(), a.marker()), (0, 0, true));
assert_eq!((b.sequence(), b.timestamp(), b.marker()), (1, OPUS_20_MS_TICKS, false));
assert_eq!((a.ssrc(), a.payload_type()), (first.flow.0, PT_OPUS));
assert_eq!(a.payload(), OPUS_20_MS);
}
#[test]
fn the_end_is_one_empty_packet_and_the_next_spurt_has_a_marker() {
let mut up = Uplink::default();
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
let end = up.frame(8, &voice(&[])).unwrap();
assert!(view(&end).payload().is_empty() && !view(&end).marker());
assert_eq!(view(&end).sequence(), 1);
let next = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
assert!(view(&next).marker());
assert_eq!(view(&next).sequence(), 2);
}
#[test]
fn the_sequence_wraps() {
let mut up = Uplink { sequence: u16::MAX, ..Default::default() };
up.frame(8, &voice(&OPUS_20_MS)).unwrap();
let wrapped = up.frame(8, &voice(&OPUS_20_MS)).unwrap();
assert_eq!(view(&wrapped).sequence(), 0);
}
#[test]
fn received_voice_is_split_into_slot_sub_flow_sequence_and_codec() {
let flow = FlowId::new(9, 0);
let mut header = RtpHeader::new(PT_OPUS, 513, 0);
header.marker = true;
let mut rtp = BytesMut::new();
header.write(flow, &mut rtp).unwrap();
rtp.extend_from_slice(&OPUS_20_MS);
let packet = MediaPacket { flow, rtp: rtp.freeze() };
let got = Incoming::parse(&packet).unwrap();
assert_eq!(
got,
Incoming {
slot: 9,
whisper: false,
sequence: 513,
codec: VoiceCodec::Voice,
payload: OPUS_20_MS.to_vec()
}
);
let voice = got.voice(8);
assert_eq!((voice.talker, voice.seq, voice.whisper), (TalkerId(8), 513, false));
}
#[test]
fn whispers_stereo_ends_and_what_is_no_voice() {
let packet = |flow: FlowId, payload: &[u8]| {
let mut rtp = BytesMut::new();
RtpHeader::new(PT_OPUS, 1, 0).write(flow, &mut rtp).unwrap();
rtp.extend_from_slice(payload);
MediaPacket { flow, rtp: rtp.freeze() }
};
assert!(Incoming::parse(&packet(FlowId::new(9, 3), &OPUS_20_MS)).unwrap().whisper);
assert!(!Incoming::parse(&packet(FlowId::new(9, 7), &OPUS_20_MS)).unwrap().whisper);
let stereo = [OPUS_20_MS[0] | 0x04, 1, 2];
assert_eq!(
Incoming::parse(&packet(FlowId::new(9, 0), &stereo)).unwrap().codec,
VoiceCodec::Music
);
let end = Incoming::parse(&packet(FlowId::new(9, 0), &[])).unwrap();
assert!(end.payload.is_empty() && end.voice(8).is_end());
// Feedback and probes are no voice.
assert!(
Incoming::parse(&MediaPacket { flow: FlowId::FEEDBACK, rtp: Default::default() })
.is_none()
);
assert!(
Incoming::parse(&MediaPacket { flow: FlowId::PROBE, rtp: Default::default() })
.is_none()
);
assert!(
Incoming::parse(&MediaPacket { flow: FlowId::new(9, 0), rtp: vec![1, 2].into() })
.is_none()
);
}
#[test]
fn a_talker_starts_with_a_packet_and_stops_400_ms_after_its_last() {
let mut talk = TalkTracker::default();
let t0 = Instant::now();
assert!(talk.heard(8, t0));
assert!(!talk.heard(8, t0 + Duration::from_millis(100)), "already talking");
assert!(talk.heard(9, t0 + Duration::from_millis(150)));
assert!(talk.is_talking(8));
// 399 ms after 8's last packet: still talking.
assert!(talk.expire(t0 + Duration::from_millis(499)).is_empty());
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [8]);
assert!(!talk.is_talking(8) && talk.is_talking(9));
assert_eq!(talk.expire(t0 + Duration::from_millis(551)), [9]);
// A packet after the silence starts it again.
assert!(talk.heard(8, t0 + Duration::from_secs(2)));
}
#[test]
fn a_host_that_says_someone_talks_is_believed_until_it_says_otherwise() {
let mut talk = TalkTracker::default();
let t0 = Instant::now();
// A talker whose voice is no media: on, and no silence ends it.
assert!(talk.hint(8, true));
assert!(!talk.hint(8, true), "already talking");
assert!(talk.is_talking(8));
assert!(talk.expire(t0 + Duration::from_secs(60)).is_empty());
assert!(talk.hint(8, false));
assert!(!talk.is_talking(8));
// A talker with media that the host also names: the media ends it, when
// the host has said it is over (in either order).
assert!(talk.heard(9, t0));
assert!(!talk.hint(9, true), "heard already");
assert!(talk.expire(t0 + Duration::from_millis(500)).is_empty(), "the host still says so");
assert!(talk.is_talking(9));
assert!(talk.hint(9, false));
assert!(!talk.is_talking(9));
assert!(talk.heard(10, t0));
assert!(!talk.hint(10, false), "the media goes on");
assert_eq!(talk.expire(t0 + Duration::from_millis(500)), [10]);
// A hint about somebody who is gone is forgotten.
assert!(talk.hint(11, true));
talk.retain_hints(|client| client != 11);
assert!(!talk.is_talking(11));
}
}
+330
View File
@@ -0,0 +1,330 @@
//! The engine's seam to the server its voice source talks to.
//!
//! A session merges up to three sources (voice, gateway, query). The *voice*
//! source is the connection that is visible on the server, can talk and
//! carries chat, files, pokes, offline messages and streams. The engine holds
//! it as a `voelin_proto::link::Session`, the backend-neutral interface of the
//! protocol repository, and knows nothing else of the server software behind
//! it: which backend makes the `Session` is the scheme of the address, and
//! [`Backends`] is the registry of connectors by scheme
//! ([`Backends::default`] has the TeamSpeak one,
//! [`crate::ts::TsConnector`]; a Voelin host's QUIC connector will be
//! another). [`VoiceOptions`] says what to connect to and as whom.
//!
//! Inside the crate `session.rs` merges and routes, and an adapter below it
//! turns what it asks into `Session` calls and what the `Session` pushes into
//! what it hears (`link/session_link.rs`, with `project.rs` and `media.rs`);
//! `docs/session-seam.md` describes the mapping row by row.
mod backends;
mod connect;
#[cfg(test)]
mod fake_link_tests;
#[cfg(test)]
mod fake_tests;
pub(crate) mod media;
pub(crate) mod project;
mod session_link;
#[cfg(test)]
mod tests;
pub use backends::Backends;
pub(crate) use backends::{
LocalConnected, LocalConnector, LocalCtx, StreamEvent, StreamPort, without_query,
};
pub(crate) use connect::{VERSION_PARAM, connect_params};
pub(crate) use session_link::SessionLink;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::sync::{broadcast, oneshot};
use voelin_audio::{EncodedVoice, VoicePacket};
use voelin_identity::IdentityBlob;
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, Presence};
use voelin_stream::PeerConfig;
use crate::files::{Report, RequestId, Sink, TransferId};
use crate::settings::SharedSettings;
use crate::stream::{OwnStreamEvent, StreamCmd, StreamFrame};
use crate::{BackendInfo, Event, SessionId};
/// What a voice connection needs to know: the server, who to be, where to
/// join ([`Command::ConnectVoice`](crate::Command::ConnectVoice)).
///
/// Nothing in it belongs to one kind of server: what a connector needs of it
/// that is its own (a TeamSpeak identity, the client version to claim) is in
/// the `identity` blob and the `client_version` spec, which the connector of
/// the address reads.
#[derive(Clone, Debug)]
pub struct VoiceOptions {
/// The server: `host[:port]` of a TeamSpeak bookmark, or an address with a
/// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`)
/// that picks the connector ([`Backends`]).
pub address: String,
/// The name shown on the server: `Hello.nickname` to a Voelin host, the
/// client name on a TeamSpeak server (which may refuse or change it). When
/// it is empty, the `nickname` parameter of an `address` that is a
/// TeamSpeak link applies.
pub nickname: String,
/// The identity to connect with: a TeamSpeak identity
/// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key
/// for a Voelin host. None lets the connector make one up (a TeamSpeak
/// connection generates an identity, which a server then knows as a new
/// client).
pub identity: Option<IdentityBlob>,
/// The client version a TeamSpeak server is shown, as a spec for
/// [`crate::ts::versions::resolve`] (`default`, `generic`, an index, or
/// `<platform>@<version>`); `None` is the native platform's. A spec that is
/// none ends the connect with the reason. Other backends ignore it.
pub client_version: Option<String>,
/// The password of the server (`Hello.password`), for one that has a
/// password. When it is `None` or empty, the `password` parameter of an
/// `address` that is a TeamSpeak link applies. Not the password of
/// `channel` (that is `channel_password`).
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections (TeamSpeak 6).
pub stream_peer: PeerConfig,
}
impl VoiceOptions {
/// Options for `address` and `nickname`; everything else is left to the
/// connector.
pub fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
Self {
address: address.into(),
nickname: nickname.into(),
identity: None,
client_version: None,
server_password: None,
channel: None,
channel_password: None,
token: None,
audio: false,
stream_peer: PeerConfig::default(),
}
}
}
/// What the engine gives a link besides the options: where the connection
/// answers the requests the session need not see, and what it shares with
/// the session's other parts.
#[derive(Clone)]
pub(crate) struct LinkCtx {
pub(crate) session: SessionId,
pub(crate) events: broadcast::Sender<Event>,
/// The frames of watched streams (kept off the event bus).
pub(crate) frames: broadcast::Sender<StreamFrame>,
pub(crate) settings: SharedSettings,
}
impl LinkCtx {
/// The session this connection belongs to.
pub(crate) fn session(&self) -> SessionId {
self.session
}
/// Tell the engine's event bus something (a request's answer, a
/// transfer's progress).
pub(crate) fn emit(&self, event: Event) {
let _ = self.events.send(event);
}
pub(crate) fn done(&self, request: RequestId, result: Result<(), String>) {
self.emit(Event::RequestDone { session: self.session, request, result });
}
}
/// A file on the server: channel, its password, path.
#[derive(Clone, Debug)]
pub(crate) struct Remote {
pub channel: ChannelId,
pub password: Option<String>,
pub path: String,
}
/// A boxed stream of bytes to read: the body of a file the server sends.
pub(crate) type BoxRead = Pin<Box<dyn AsyncRead + Send>>;
/// A connection that can be read and written: a file transfer connection.
pub(crate) trait Duplex: AsyncRead + AsyncWrite + Send {}
impl<T: AsyncRead + AsyncWrite + Send> Duplex for T {}
/// A boxed [`Duplex`].
pub(crate) type BoxDuplex = Pin<Box<dyn Duplex>>;
/// What the session asks of a connection.
pub(crate) enum LinkCmd {
SendChat(ChatTarget, String),
Move(ChannelId, Option<String>),
SetInputMuted(bool),
SetOutputMuted(bool),
/// An encoded voice frame from the audio thread.
Audio(EncodedVoice),
/// A stream command; the link answers on the event bus. Only sent while
/// the connection's capabilities include streams.
Stream(StreamCmd),
Poke {
client: u16,
message: String,
},
ListFiles {
request: RequestId,
dir: Remote,
},
/// Download `file`; `transfer` if the user can cancel it.
Download {
transfer: Option<TransferId>,
file: Remote,
sink: Sink,
report: Report,
},
Upload {
transfer: Option<TransferId>,
file: Remote,
from: PathBuf,
overwrite: bool,
resume: bool,
report: Report,
},
CancelTransfer(TransferId),
/// Open a file of the server for reading, from `offset`: the transfer
/// connection itself, and the file's size in all, once the server has
/// agreed (the text of the failure otherwise). The engine copies the
/// bytes, reports the progress and cancels by dropping the connection, so
/// this does not use [`LinkCmd::Download`]'s sink and report.
OpenRead {
file: Remote,
offset: u64,
reply: oneshot::Sender<Result<(u64, BoxRead), String>>,
},
/// Open a file of the server for writing: the transfer connection and the
/// position the server wants the bytes from (the size it already has, if
/// `resume`). The engine writes the bytes and ends the connection.
OpenWrite {
file: Remote,
/// The file's size in all.
size: u64,
overwrite: bool,
resume: bool,
reply: oneshot::Sender<Result<(u64, BoxDuplex), String>>,
},
DeleteFiles {
/// `None`: best effort, nobody waits for the answer.
request: Option<RequestId>,
channel: ChannelId,
password: Option<String>,
paths: Vec<String>,
},
RenameFile {
request: RequestId,
from: Remote,
to: Remote,
},
CreateDirectory {
request: RequestId,
dir: Remote,
},
/// Announce our avatar's hash (empty: no avatar).
SetAvatarHash {
request: Option<RequestId>,
hash: String,
},
OfflineList {
request: RequestId,
},
OfflineGet {
request: RequestId,
id: u32,
},
OfflineAdd {
request: RequestId,
to_uid: String,
subject: String,
text: String,
},
OfflineDelete {
request: RequestId,
id: u32,
},
OfflineFlag {
request: RequestId,
id: u32,
read: bool,
},
Disconnect,
}
/// What a connection tells the session.
pub(crate) enum LinkEvent {
Connected {
name: String,
/// The server software, and what it can do (the connection knows
/// both from the server's version).
backend: BackendInfo,
capabilities: Capabilities,
/// Our client id when the link connected. TeamSpeak's own reconnect gives
/// a new one, which is not announced; the engine follows it in the
/// snapshots by our unique id.
own_client: u16,
/// The server's unique id.
server_uid: String,
/// Our unique id as the server knows it.
own_uid: Option<String>,
},
/// The server's channels and clients as they are now.
Presence(Box<Presence>),
/// The channel we are in, after every [`LinkEvent::Presence`]. The engine
/// derives it itself, from our own voice state in the snapshots of the
/// `Session` it talks to, and so follows us when TeamSpeak's reconnect makes
/// us another client. What an in-process link such as `TsLink` says here only
/// tells the TeamSpeak `Session` made of it that a move has arrived.
OwnChannel(ChannelId),
Chat(ChatMessage),
Poke {
from: u16,
from_uid: Option<String>,
from_name: String,
message: String,
},
/// Incoming voice for the audio thread.
Audio(VoicePacket),
/// Who is talking (on, and off again when it stopped). The engine derives
/// it from the media of its `Session` (protocol section 6.4). What an
/// in-process link such as `TsLink` says here reaches the engine as a
/// speaking hint next to the media: that is what shows the talkers whose
/// packets the link does not forward as Opus (Speex, CELT).
Talking {
client: u16,
talking: bool,
},
/// Our own stream's life, for the gateway directory.
OwnStream(OwnStreamEvent),
/// An Opus frame (48 kHz) of a watched stream, for the audio thread
/// ([`VoiceOptions::audio`]); `time` is its RTP time on the 48 kHz
/// clock.
StreamAudio {
stream: String,
time: u64,
data: Arc<[u8]>,
},
/// A watched stream ended: its audio leaves the mixer.
StreamAudioEnded(String),
/// A command failed (the connection stays).
Error(String),
/// The connection ended; the reason if it was not asked for. Sent once;
/// the stream task's closing reports may still follow (see the module
/// documentation).
Disconnected(Option<String>),
}
+214
View File
@@ -0,0 +1,214 @@
//! The engine's view of a session's replica, in the client's older model
//! (`docs/session-seam.md` section 5.3).
//!
//! The UI and `session.rs` still speak `Presence`, `ChannelInfo`,
//! `ClientInfo`, `ServerDetails` and `ChatMessage`. [`presence`] and
//! [`chat_message`] project the replica into them with
//! `voelin_model::replica::convert`, and fix up where that says less than the
//! older model does (F1 to F10 of the design). The fix-ups apply the
//! TeamSpeak gateway's id rules of protocol section 11.1, so the UI keeps the
//! ids it has; they go when the UI reads the replica.
use std::collections::BTreeMap;
use voelin_model::replica::{Replica, convert};
use voelin_model::{ChatMessage, ChatTarget, GroupInfo, Presence, ServerDetails};
use voelin_proto::link::Features;
use voelin_proto::v1::{self, ChannelKind, MessageFlag, RoleScope};
use super::media::TalkTracker;
use crate::ts::ts_session::entities::user_uid;
use crate::ts::ts_session::ids::{self, FOREIGN_SYSTEM};
/// What the projection needs to know besides the replica.
pub(crate) struct View<'a> {
pub(crate) replica: &'a Replica,
/// The server of the session.
pub(crate) server: u64,
/// The backend is TeamSpeak (`Welcome.host.backend.product`): its id rules
/// (channel groups) are undone.
pub(crate) teamspeak: bool,
/// The version the host said (`Welcome.host.backend.version`).
pub(crate) version: &'a str,
pub(crate) features: &'a Features,
/// Whether the connection has streams (a port, not just the feature).
pub(crate) streams: bool,
pub(crate) talking: &'a TalkTracker,
}
/// What a `Foreign` of TeamSpeak holds under `key`.
fn foreign_value(
foreign: Option<&v1::Foreign>,
kind: &str,
key: &str,
) -> Option<serde_json::Value> {
let foreign = foreign.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == kind)?;
serde_json::from_slice::<serde_json::Value>(&foreign.json).ok()?.get(key).cloned()
}
/// The server's unique id as the client keys its history and aliases by it:
/// the host's without the `ts:` of protocol section 11.2 (F3).
pub(crate) fn server_key(uid: &str) -> String {
uid.strip_prefix("ts:").unwrap_or(uid).to_owned()
}
/// The client's older model of the server (what `LinkEvent::Presence` holds).
pub(crate) fn presence(view: &View<'_>) -> Presence {
let replica = view.replica;
let server = view.server;
// F1: only what the older model calls channels.
let channels: Vec<&v1::Channel> = replica
.channels(server)
.filter(|channel| {
!matches!(
ChannelKind::try_from(channel.kind),
Ok(ChannelKind::ServerChat
| ChannelKind::Dm
| ChannelKind::GroupDm
| ChannelKind::Thread)
)
})
.collect();
let by_id: BTreeMap<u64, &v1::Channel> = channels.iter().map(|c| (c.id, *c)).collect();
let channel_infos = convert::channel_infos(&channels)
.into_iter()
.map(|mut info| {
// F7: a limit of 0 is a limit, not "unlimited".
let zero = by_id
.get(&info.id)
.and_then(|c| foreign_value(c.foreign.as_ref(), "channel", "max_clients"));
if zero.and_then(|v| v.as_i64()) == Some(0) {
info.max_clients = Some(0);
}
(info.id, info)
})
.collect();
let clients = replica
.voice_states(server)
.filter_map(|voice| {
let user = replica.user(voice.user_id);
let member = replica.member(server, voice.user_id);
let mut client =
convert::client_info(voice, user, member, replica.presence_of(voice.user_id))?;
// F10: a unique id that is no base64 rides in `Foreign`.
client.uid = user.and_then(user_uid);
// F2: the client's channel group is TeamSpeak's own number.
if view.teamspeak {
client.channel_group = client.channel_group.map(ids::channel_group);
}
// F6: the client's icon.
client.icon = foreign_value(member.and_then(|m| m.foreign.as_ref()), "client", "icon")
.and_then(|v| v.as_u64())
.and_then(|v| u32::try_from(v).ok())
.unwrap_or(0);
// F8: who is talking comes from the media.
client.talking = view.features.has("voice").then(|| view.talking.is_talking(client.id));
// F9: the stream flag only where there are streams.
if !view.streams {
client.streaming = None;
}
Some((client.id, client))
})
.collect();
let mut server_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
let mut channel_groups: BTreeMap<u64, GroupInfo> = BTreeMap::new();
for role in replica.roles(server) {
let mut info = convert::group_info(role);
if role.scope == RoleScope::Channel as i32 {
if view.teamspeak {
info.id = ids::channel_group(info.id);
}
channel_groups.insert(info.id, info);
} else {
server_groups.insert(info.id, info);
}
}
let details = replica.server(server).map(|stub| server_details(view, stub)).unwrap_or_default();
Presence {
server_name: details.name.clone(),
channels: channel_infos,
clients,
server: details,
server_groups,
channel_groups,
}
}
/// `convert::server_details` with F2 to F5.
fn server_details(view: &View<'_>, server: &v1::Server) -> ServerDetails {
let mut details = convert::server_details(server);
// F3: the unique id as the client keys it.
details.uid = details.uid.as_deref().map(server_key);
let foreign = server.foreign.as_ref();
// F4: the version the server sent, else the one the host reports.
details.version = foreign_value(foreign, "server", "version")
.and_then(|v| v.as_str().map(str::to_owned))
.filter(|v| !v.is_empty())
.unwrap_or_else(|| view.version.to_owned());
// F5: the server's platform.
details.platform = foreign_value(foreign, "server", "platform")
.and_then(|v| v.as_str().map(str::to_owned))
.unwrap_or_default();
// F2: the default channel group is TeamSpeak's own number.
if view.teamspeak {
details.default_channel_group = details.default_channel_group.map(ids::channel_group);
}
details
}
/// Where the older model files the messages of a channel (the replica's
/// `chat_target`, with the unique id of F10).
fn chat_target(replica: &Replica, channel: u64) -> ChatTarget {
let Some(info) = replica.channel(channel) else { return ChatTarget::Channel(channel) };
match ChannelKind::try_from(info.kind) {
Ok(ChannelKind::ServerChat) => ChatTarget::Server,
Ok(ChannelKind::Dm | ChannelKind::GroupDm) => {
let own = replica.own_user();
info.recipients
.iter()
.copied()
.find(|id| *id != own)
.and_then(|id| replica.user(id))
.and_then(user_uid)
.map_or(ChatTarget::Channel(channel), ChatTarget::Private)
}
_ => ChatTarget::Channel(channel),
}
}
/// A message of the replica as the older model has it.
pub(crate) fn chat_message(replica: &Replica, channel: u64, id: u64) -> Option<ChatMessage> {
let message = replica.message(channel, id)?;
let author = replica.user(message.author_id);
let name = Some(message.author_name.as_str())
.filter(|name| !name.is_empty())
.or_else(|| author.map(|u| u.name.as_str()).filter(|name| !name.is_empty()))
.unwrap_or_default();
Some(ChatMessage {
target: chat_target(replica, channel),
author_name: name.to_owned(),
author_uid: author.and_then(user_uid),
author_id: (message.author_participant != 0)
.then(|| u16::try_from(message.author_participant).ok())
.flatten(),
text: message.text.clone(),
ts_ms: message.ts_ms,
via_relay: message.flags & MessageFlag::Relayed as u32 != 0,
blocked: false,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_ts_prefix_of_a_server_uid_goes() {
assert_eq!(server_key("ts:abc="), "abc=");
assert_eq!(server_key("abc="), "abc=");
assert_eq!(server_key(""), "");
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+137 -44
View File
@@ -2680,7 +2680,7 @@ pub struct DecodeStats {
pub bytes: u64,
/// Pictures decoded per second and video received in bit/s, over the
/// time since the previous [`VideoPipeline::stats`] (at least
/// [`RATE_WINDOW`]; the watch screen asks once a second).
/// `RATE_WINDOW`; the watch screen asks once a second).
pub fps: u32,
pub bitrate: u64,
}
@@ -3257,9 +3257,13 @@ impl LocalPreview {
}
/// The first and last column of the rectangle in the middle row of a
/// decoded test pattern. Checks that pixels further than two columns from
/// its edges (which the codec blurs) have the colour of the rectangle or
/// the background.
/// decoded test pattern, after checking the row's structure: background, one
/// run of the rectangle, background. A pixel is whichever of the pattern's two
/// colours it is nearer to; it is not asked to be within some distance of one,
/// because an encoder that falls behind lowers its quality (the VP8 speed
/// control of the streamer does) and then moves a flat colour by 30 and more
/// per channel, still nowhere near the other colour. The two columns at each
/// edge, which the codec blurs, may be either.
#[cfg(all(test, feature = "media-desktop"))]
pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
use voelin_media::capture::synthetic::{BACKGROUND, RECT_COLOR};
@@ -3270,15 +3274,23 @@ pub(crate) fn rectangle_span(picture: &VideoFrame) -> (u32, u32) {
let i = ((y * picture.width + x) * 4) as usize;
[rgba[i], rgba[i + 1], rgba[i + 2]]
};
let close = |p: [u8; 3], c: [u8; 3]| p.iter().zip(c).all(|(a, b)| a.abs_diff(b) <= 24);
let inside: Vec<u32> = (0..picture.width).filter(|&x| close(pixel(x), RECT_COLOR)).collect();
let (&a, &b) = inside.first().zip(inside.last()).expect("no rectangle in the middle row");
for x in 0..picture.width {
if x + 2 < a || x > b + 2 {
assert!(close(pixel(x), BACKGROUND), "pixel {x},{y} is {:?}", pixel(x));
} else if (a + 2..=b.saturating_sub(2)).contains(&x) {
assert!(close(pixel(x), RECT_COLOR), "pixel {x},{y} is {:?}", pixel(x));
}
let distance = |p: [u8; 3], c: [u8; 3]| -> u32 {
p.iter().zip(c).map(|(a, b)| u32::from(a.abs_diff(b)).pow(2)).sum()
};
let rectangle = |x: u32| {
let p = pixel(x);
distance(p, RECT_COLOR) < distance(p, BACKGROUND)
};
let a = (0..picture.width).find(|&x| rectangle(x)).expect("no rectangle in the middle row");
let b = (0..picture.width).rfind(|&x| rectangle(x)).unwrap();
// One run: everything between its ends, but the blurred edges, is the
// rectangle's. Whatever is outside is the background by the choice of a and b.
for x in a + 2..=b.saturating_sub(2) {
assert!(
rectangle(x),
"pixel {x},{y} is {:?}, in the middle of the rectangle (columns {a} to {b})",
pixel(x)
);
}
(a, b)
}
@@ -3410,7 +3422,14 @@ mod tests {
assert!(all.is_hardware(backend), "{codec} offered in software");
}
if all.encoder_codecs().contains(&Codec::H264) && !offer.contains(&Codec::H264) {
assert_eq!(offer_codecs(&all, Codec::H264)[..2], [Codec::H264, Codec::Vp8]);
// H.264 in software only (so not in `offer`): it leads the same
// codecs as with VP8 as the stream codec, whichever hardware
// encoders this machine has (a hardware AV1 or VP9 encoder ranks
// before VP8, so VP8 is not always second).
let h264 = offer_codecs(&all, Codec::H264);
assert_eq!(h264[0], Codec::H264, "{h264:?}");
assert_eq!(h264.len(), offer.len() + 1, "{h264:?} against {offer:?}");
assert!(offer.iter().all(|c| h264.contains(c)), "{h264:?} against {offer:?}");
}
// Whatever this machine has: codecs every TeamSpeak client decodes
// come before H.264, HEVC last, and the automatic stream codec is
@@ -3423,10 +3442,23 @@ mod tests {
let ranks: Vec<_> = offer[1..].iter().map(rank).collect();
assert!(ranks.is_sorted(), "{offer:?}");
assert!(preferred_codec(&all, None).is_some_and(decoded_everywhere), "{all:?}");
assert_eq!(
preferred_codec(&all, Some(Codec::H264)).is_some(),
all.encoder_codecs().contains(&Codec::H264)
);
// A configured codec is the stream codec when this machine can encode
// it; otherwise the result is the automatic choice,
// `preferred_codec(&all, None)` (some codec on any machine that
// encodes anything). Whether H.264 is encodable depends on the
// machine (a desktop with FFmpeg or a GPU has an encoder, a CI
// runner has none), so the expectation follows `all.encoder_codecs()`.
let h264 = preferred_codec(&all, Some(Codec::H264));
if all.encoder_codecs().contains(&Codec::H264) {
assert_eq!(h264, Some(Codec::H264), "{all:?}");
} else {
assert_eq!(h264, preferred_codec(&all, None), "{all:?}");
}
// The built-in codecs are the same everywhere (no OpenH264 loaded):
// VP9 is encodable and wins, H.264 is not and falls back to VP8.
assert_eq!(preferred_codec(&codecs, Some(Codec::Vp9)), Some(Codec::Vp9));
assert_eq!(preferred_codec(&codecs, Some(Codec::H264)), preferred_codec(&codecs, None));
assert_eq!(preferred_codec(&codecs, None), Some(Codec::Vp8));
}
/// A sink whose viewers chose `codecs`; keeps every video frame with its
@@ -3516,11 +3548,30 @@ mod tests {
};
told(30).await;
assert_eq!(streamer.bitrate_kbps(), 1105);
// Not per frame.
let count = lock(&sink.formats).len();
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(lock(&sink.formats).len(), count);
assert_eq!(streamer.stats().layers[0].bitrate, auto_bitrate(640, 480, 30));
// Not per frame. The sink is told when it is attached and again by the
// encoder before its first frame (the same format twice), so the count is
// taken once a frame has been handed over and compared after more have;
// the frames, not a pause, are what "per frame" counts.
let frames_by = |frames: u64| {
let streamer = &streamer;
async move {
let deadline = Instant::now() + Duration::from_secs(30);
while streamer.stats().layers[0].frames < frames {
assert!(Instant::now() < deadline, "{frames} frames: {:?}", streamer.stats());
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
};
frames_by(1).await;
let (count, seen) = (lock(&sink.formats).len(), streamer.stats().layers[0].frames);
frames_by(seen + 5).await;
assert_eq!(lock(&sink.formats).len(), count, "told again within five frames");
// The stats follow the sink's being told, not the other way round.
let deadline = Instant::now() + Duration::from_secs(10);
while streamer.stats().layers[0].bitrate != auto_bitrate(640, 480, 30) {
assert!(Instant::now() < deadline, "{:?}", streamer.stats().layers);
tokio::time::sleep(Duration::from_millis(20)).await;
}
let update = StreamerConfigUpdate { fps: Some(15), ..StreamerConfigUpdate::default() };
streamer.reconfigure(&codecs, update).unwrap();
told(15).await;
@@ -3691,15 +3742,35 @@ mod tests {
assert!((60..=68).contains(&(b - a + 1)), "{spans:?}");
}
assert_ne!(spans.first(), spans.last(), "the rectangle moves");
let stats = preview.stats();
assert!(stats.decoded >= 10 && stats.error.is_none(), "{stats:?}");
assert_eq!(stats.codec, Some(Codec::Vp8));
let (before_first, first) = (Instant::now(), preview.stats());
let after_first = Instant::now();
assert!(first.decoded >= 10 && first.error.is_none(), "{first:?}");
assert_eq!(first.codec, Some(Codec::Vp8));
assert_eq!(preview.streamer().backend(), "synthetic");
// Rates over the second since: the pattern's rate, its bitrate.
// The rates are the counters over the time since the call before. How
// long that was the test does not say (a busy machine stretches a second,
// and the rate of pictures it manages is not what is tested), but it lies
// between the two spans the test timed around it.
tokio::time::sleep(Duration::from_secs(1)).await;
let stats = preview.stats();
assert!((20..=40).contains(&stats.fps), "{stats:?}");
assert!((100_000..5_000_000).contains(&stats.bitrate), "{stats:?}");
let before_second = Instant::now();
let second = preview.stats();
let after_second = Instant::now();
let longest = after_second.duration_since(before_first).as_secs_f64();
let shortest = before_second.duration_since(after_first).as_secs_f64();
let frames = (second.decoded - first.decoded) as f64;
let bits = (second.bytes - first.bytes) as f64 * 8.0;
assert!(frames > 0.0, "no picture in the second: {first:?} {second:?}");
// (The pictures per second are rounded, the bits per second cut off.)
let fps = f64::from(second.fps);
assert!(
(frames / longest - 0.5..=frames / shortest + 0.5).contains(&fps),
"{frames} pictures in {shortest} to {longest} s are not {fps} a second"
);
let bitrate = second.bitrate as f64;
assert!(
(bits / longest - 1.0..=bits / shortest).contains(&bitrate),
"{bits} bits in {shortest} to {longest} s are not {bitrate} a second"
);
}
/// A VP8 decoder for the pipeline tests: fails (with errors, or giving
@@ -4123,7 +4194,8 @@ mod tests {
};
let streamer = Streamer::start(&codecs, config).await.unwrap();
let wait = |what: &str, done: &dyn Fn(&StreamerStats) -> bool| {
let deadline = Instant::now() + Duration::from_secs(5);
// What is waited for is a state; the deadline only ends a hang.
let deadline = Instant::now() + Duration::from_secs(30);
loop {
let stats = streamer.stats();
if done(&stats) {
@@ -4133,15 +4205,18 @@ mod tests {
std::thread::sleep(Duration::from_millis(20));
}
};
// The SineSource tone is 0.05; the second at half gain.
// The SineSource tone is 0.05; the second at half gain. The sources are metered
// before the mixer has made anything of them: the mix and the state of the
// sources are waited for too, not taken to be there with the meters.
let near = |level: f32, want: f32| (level - want).abs() < want * 0.1;
let stats = wait("both tones", &|s| {
let stats = wait("both tones, mixed", &|s| {
s.audio_sources.len() == 2
&& near(s.audio_sources[0].level.peak, 0.05)
&& near(s.audio_sources[1].level.peak, 0.025)
&& s.audio_sources.iter().all(|s| s.state == SourceState::Playing)
&& s.audio_level.peak > 0.05
&& s.audio_limiter == 1.0
});
assert!(stats.audio_sources.iter().all(|s| s.state == SourceState::Playing));
assert!(stats.audio_level.peak > 0.05 && stats.audio_limiter == 1.0, "{stats:?}");
let first = stats.audio_sources[0].id;
// Mute the first (kept: same id), drop the second, add the
@@ -4157,19 +4232,31 @@ mod tests {
streamer.reconfigure(&codecs, update).unwrap();
assert_eq!(streamer.audio_sources().len(), 3);
let publisher = tap::publisher_id();
let speak = std::thread::spawn(move || {
// 20 ms of a 0.2 tone every 20 ms, for a second.
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
for _ in 0..50 {
tap::microphone().publish(publisher, &chunk);
std::thread::sleep(Duration::from_millis(20));
let heard = Arc::new(AtomicBool::new(false));
let speak = std::thread::spawn({
let heard = heard.clone();
move || {
// 20 ms of a 0.2 tone every 20 ms, until the test has heard it: the
// source takes what is published only from when it runs, which a
// busy machine delays by any time (the cap ends a thread whose test
// failed first).
let cap = Instant::now() + Duration::from_secs(120);
let chunk: Vec<f32> = (0..960).map(|i| 0.2 * (i as f32 * 0.1).sin()).collect();
while !heard.load(Ordering::Relaxed) && Instant::now() < cap {
tap::microphone().publish(publisher, &chunk);
std::thread::sleep(Duration::from_millis(20));
}
}
});
let stats = wait("microphone in, tone muted", &|s| {
s.audio_sources.len() == 3
&& s.audio_sources[1].level.peak > 0.15
&& s.audio_level.peak > 0.15
&& s.audio_sources[2].error.as_deref().is_some_and(|e| e.contains("no window"))
// Muted, and still metered: the tone's own level is read again.
&& near(s.audio_sources[0].level.peak, 0.05)
});
heard.store(true, Ordering::Relaxed);
speak.join().unwrap();
assert_eq!(stats.audio_sources[0].id, first, "the kept tone keeps its source");
assert!(stats.audio_sources[0].spec.muted);
@@ -4201,9 +4288,15 @@ mod tests {
assert!(streamer.has_audio(), "{:?}", streamer.audio_error());
let mut source = EncodedSource::new(streamer);
let mut frames = Vec::new();
let deadline = Instant::now() + Duration::from_secs(5);
while frames.iter().filter(|f: &&EncodedFrame| f.kind == MediaKind::Audio).count() < 10 {
assert!(Instant::now() < deadline, "no audio");
// Ten frames of audio and one of video, whichever the encoders make first:
// 20 ms of audio is quickly made, and a busy machine can keep the video
// encoder from its first frame for longer than that. The deadline only ends
// a hang.
let deadline = Instant::now() + Duration::from_secs(30);
let count =
|frames: &[EncodedFrame], kind| frames.iter().filter(|f| f.kind == kind).count();
while count(&frames, MediaKind::Audio) < 10 || count(&frames, MediaKind::Video) < 1 {
assert!(Instant::now() < deadline, "no audio or no video in {} frames", frames.len());
tokio::time::sleep(Duration::from_millis(20)).await;
source.poll_frames(Instant::now(), &mut frames);
}
+141 -1
View File
@@ -1,11 +1,94 @@
//! The query source: own ServerQuery credentials, in-process observer and relays.
use std::fmt;
use tokio::sync::{broadcast, mpsc};
use voelin_model::{ChatMessage, ChatTarget, Presence};
use voelin_observer::{
Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool,
};
/// How a ServerQuery connection talks to the server.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QueryTransport {
/// The raw text protocol (TeamSpeak 3; port 10011).
Raw,
/// SSH.
Ssh,
/// The HTTP query (TeamSpeak 6; a WebQuery API key is the secret).
Http,
}
/// The user's own ServerQuery credentials for a server
/// ([`Command::ObserveQuery`](crate::Command::ObserveQuery)): what the
/// engine logs in with to observe a server invisibly and to relay its
/// channels' chat. The connection's own tuning (flood protection, timeouts)
/// is the engine's.
#[derive(Clone, PartialEq, Eq)]
pub struct QueryLogin {
/// The protocol of the query interface at `address`.
pub transport: QueryTransport,
/// `host:port` of the query interface.
pub address: String,
/// The login name (raw and SSH; ignored for HTTP).
pub user: String,
/// The password (raw and SSH) or API key (HTTP, optional for guest access).
pub secret: Option<String>,
/// Select the virtual server by its voice port...
pub server_port: Option<u16>,
/// ...or by id (the first server when neither is given).
pub server_id: Option<u32>,
/// This machine's address is on the server's query allowlist, which the
/// server's flood protection skips: the engine then sends its commands
/// without the limit it keeps for a server that has not said so (a command
/// the server refuses as a flood slows the connection down all the same).
/// The application usually cannot know, and says `false`; the development
/// servers of the tests allowlist their clients.
pub allowlisted: bool,
}
impl fmt::Debug for QueryLogin {
// The secret is kept out of logs.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("QueryLogin")
.field("transport", &self.transport)
.field("address", &self.address)
.field("user", &self.user)
.field("secret", &self.secret.as_ref().map(|_| "[secret]"))
.field("server_port", &self.server_port)
.field("server_id", &self.server_id)
.field("allowlisted", &self.allowlisted)
.finish()
}
}
impl QueryLogin {
/// The connection the observer and the relays open.
fn connect(&self) -> voelin_query::Connect {
voelin_query::Connect {
transport: match self.transport {
QueryTransport::Raw => voelin_query::Transport::Raw,
QueryTransport::Ssh => voelin_query::Transport::Ssh,
QueryTransport::Http => voelin_query::Transport::Http,
},
addr: self.address.clone(),
user: self.user.clone(),
secret: self.secret.clone(),
server_port: self.server_port,
server_id: self.server_id,
line: voelin_query::LineOptions {
// Off the client-side limit only where the server skips it.
rate_limit: if self.allowlisted {
None
} else {
voelin_query::LineOptions::default().rate_limit
},
..Default::default()
},
}
}
}
pub(crate) enum QueryCmd {
OpenChat(ChatTarget),
CloseChat(ChatTarget),
@@ -21,10 +104,11 @@ pub(crate) enum QueryEvent {
}
pub(crate) async fn run(
connect: voelin_query::Connect,
login: QueryLogin,
mut commands: mpsc::UnboundedReceiver<QueryCmd>,
events: mpsc::UnboundedSender<QueryEvent>,
) {
let connect = login.connect();
let observer = Observer::spawn(ObserverConfig::new(connect.clone()));
let relays = RelayPool::new(RelayConfig::new(connect));
let mut observed = observer.subscribe();
@@ -88,3 +172,59 @@ pub(crate) async fn run(
relays.close_all().await;
let _ = events.send(QueryEvent::Disconnected);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_login_is_the_connection_the_query_crate_opens() {
let login = QueryLogin {
transport: QueryTransport::Ssh,
address: "ts.example.com:10022".into(),
user: "serveradmin".into(),
secret: Some("hunter2".into()),
server_port: Some(9987),
server_id: Some(3),
allowlisted: false,
};
let connect = login.connect();
assert_eq!(connect.transport, voelin_query::Transport::Ssh);
assert_eq!(
(connect.addr.as_str(), connect.user.as_str(), connect.secret.as_deref()),
("ts.example.com:10022", "serveradmin", Some("hunter2"))
);
assert_eq!((connect.server_port, connect.server_id), (Some(9987), Some(3)));
for (ours, theirs) in [
(QueryTransport::Raw, voelin_query::Transport::Raw),
(QueryTransport::Http, voelin_query::Transport::Http),
] {
let connect = QueryLogin { transport: ours, ..login.clone() }.connect();
assert_eq!(connect.transport, theirs);
}
// The line options are the query crate's defaults, as the UI always
// gave them, unless the server allowlists the client.
let line = voelin_query::LineOptions::default();
assert!(line.rate_limit.is_some());
assert_eq!(connect.line.rate_limit, line.rate_limit);
assert_eq!(connect.line.timeout, line.timeout);
let allowlisted = QueryLogin { allowlisted: true, ..login.clone() }.connect();
assert_eq!(allowlisted.line.rate_limit, None);
assert_eq!(allowlisted.line.timeout, line.timeout);
}
#[test]
fn the_secret_stays_out_of_the_debug_text() {
let login = QueryLogin {
transport: QueryTransport::Raw,
address: "h:1".into(),
user: "u".into(),
secret: Some("hunter2".into()),
server_port: None,
server_id: None,
allowlisted: false,
};
let text = format!("{login:?}");
assert!(!text.contains("hunter2") && text.contains("[secret]"), "{text}");
}
}
+11 -40
View File
@@ -29,7 +29,7 @@ use crate::gateway::{
Push, ReactionPush,
};
use crate::history::{self, ChatCtx, HistoryMessage, MessageSource, SharedHistory};
use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, ServerLink};
use crate::link::{LinkCmd, LinkCtx, LinkEvent, Remote, SessionLink};
use crate::query::{self, QueryCmd, QueryEvent};
use crate::route::{ChatRoute, Dedup, route_chat};
use crate::settings::{
@@ -78,31 +78,16 @@ pub(crate) struct SessionHandle {
}
impl SessionHandle {
#[allow(clippy::too_many_arguments)] // what the engine hands each session
pub fn spawn(
id: SessionId,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
link: Arc<dyn ServerLink>,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
link: Arc<SessionLink>,
) -> Self {
let (tx, rx) = mpsc::unbounded_channel();
tokio::spawn(
Session::new(
id,
events,
frames,
audio_settings,
shared,
link,
myts_identity,
myts_data,
)
.run(rx),
);
tokio::spawn(Session::new(id, events, frames, audio_settings, shared, link).run(rx));
Self { tx }
}
@@ -298,9 +283,7 @@ struct OwnStream {
struct Session {
/// Starts the voice connections.
link: Arc<dyn ServerLink>,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
link: Arc<SessionLink>,
id: SessionId,
events: broadcast::Sender<Event>,
state: SessionState,
@@ -386,24 +369,19 @@ struct Session {
}
impl Session {
#[allow(clippy::too_many_arguments)] // what the engine hands each session
fn new(
id: SessionId,
events: broadcast::Sender<Event>,
frames: broadcast::Sender<StreamFrame>,
audio_settings: AudioSettings,
shared: Shared,
link: Arc<dyn ServerLink>,
myts_identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
myts_data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
link: Arc<SessionLink>,
) -> Self {
let (sources_tx, sources_rx) = mpsc::unbounded_channel();
let Shared { settings, history, cache, contacts } = shared;
let contacts_rx = Some(contacts.watch());
Self {
link,
myts_identity,
myts_data,
cache,
contacts,
contacts_rx,
@@ -546,8 +524,6 @@ impl Session {
events: self.events.clone(),
frames: self.frames.clone(),
settings: self.settings.clone(),
myts_identity: self.myts_identity.clone(),
myts_data: self.myts_data.clone(),
};
self.link.spawn(options, ctx, cmd_rx, ev_tx);
self.forward(ev_rx, move |e| SourceEvent::Voice(generation, e));
@@ -600,7 +576,10 @@ impl Session {
// source, the history is kept under the query address.
if self.state.server_uid.is_none() {
let port = connect.server_port.map(|p| format!("/{p}")).unwrap_or_default();
self.learn_server_uid(format!("query:{}{port}", connect.addr), Source::Query);
self.learn_server_uid(
format!("query:{}{port}", connect.address),
Source::Query,
);
self.open_histories();
}
let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
@@ -873,9 +852,7 @@ impl Session {
self.voice_request(Some(request), LinkCmd::OfflineFlag { request, id, read });
}
// Engine-wide.
Command::SetMytsIdentity(_)
| Command::SetMytsData(_)
| Command::CloseSession { .. }
Command::CloseSession { .. }
| Command::TestMicrophone { .. }
| Command::SetSetting { .. }
| Command::ResetSetting { .. }
@@ -2276,19 +2253,13 @@ mod banner_tests {
cache: SharedCache::new(Cache::new(dir)),
contacts: Contacts::new(events.clone(), history),
};
// No myTeamSpeak account; its source stays open, as the engine's does
// (a closed one ends voice connections).
let myts_identity = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
let myts_data = Box::leak(Box::new(watch::Sender::new(None))).subscribe();
let session = Session::new(
1,
events,
frames,
AudioSettings::default(),
shared,
Arc::new(crate::TsLink),
myts_identity,
myts_data,
Arc::new(SessionLink::new(crate::Backends::empty())),
);
(session, receiver)
}
+1 -1
View File
@@ -1135,7 +1135,7 @@ pub static CACHE_FETCH_IMAGES: Key<bool> = Key::new(
);
/// Import identities from the official TeamSpeak clients when the app
/// starts ([`crate::identity::import_new`]; their files are only read).
/// starts ([`crate::ts::identity::import_new`]; their files are only read).
pub static IDENTITY_IMPORT: Key<bool> = Key::new(
"identity.import_from_teamspeak",
Kind::Bool,
+40 -7
View File
@@ -171,7 +171,7 @@ impl PartialEq for StreamSink {
}
}
/// What the session asks of the streams of a connection ([`crate::link::LinkCmd::Stream`]).
/// What the session asks of the streams of a connection (`LinkCmd::Stream`).
#[derive(Debug)]
pub enum StreamCmd {
Start {
@@ -1295,9 +1295,21 @@ mod tests {
// Before the viewer asks: its offer is made after this.
sink.layer_format(0, format(60_000_000));
handles[1].send(StreamCmd::Watch { stream_id: "s-1".into() });
wait(&mut rx, |e| match e {
Event::WatchState { session: 2, state: WatchState::Connected, .. } => Some(()),
_ => None,
// Connected for the viewer and for the streamer, in either order: the
// streamer asks for a keyframe when its viewer connects, a moment after
// the viewer has seen the connection.
let (mut watching, mut served) = (false, false);
wait(&mut rx, |e| {
match e {
Event::WatchState { session: 2, state: WatchState::Connected, .. } => {
watching = true;
}
Event::StreamViewers { session: 1, viewers } => {
served |= viewers.iter().any(|v| v.state == ViewerState::Connected);
}
_ => {}
}
(watching && served).then_some(())
})
.await;
// 3840x2160 at 60 fps is level 5.2 (0x34) in both profiles.
@@ -1312,7 +1324,15 @@ mod tests {
sink.take_layer_keyframes(&mut layers);
layers.contains(0)
};
keyframes();
// What asked for a keyframe so far (going live, the viewer's connecting
// and its first picture request) is done when a moment longer than the
// merging interval of requests (250 ms) passes with none.
for _ in 0..50 {
tokio::time::sleep(Duration::from_millis(300)).await;
if !keyframes() {
break;
}
}
sink.layer_format(0, format(9_000_000));
timeout(Duration::from_secs(5), async {
while !keyframes() {
@@ -1322,7 +1342,11 @@ mod tests {
.await
.expect("the layer did not change");
sink.layer_format(0, format(9_000_000));
tokio::time::sleep(Duration::from_millis(200)).await;
// The stream task takes its commands in order: its answer to this one
// (an error, nobody is viewer 65535) comes after all that the format
// above set going, and nothing is left to wait out.
handles[0].send(StreamCmd::Kick { viewer: u16::MAX });
wait(&mut rx, |e| matches!(e, Event::Error { session: 1, .. }).then_some(())).await;
assert!(!keyframes(), "nothing changed");
handles[0].send(StreamCmd::Stop);
}
@@ -1701,7 +1725,16 @@ mod tests {
let stats = pipeline.stats();
assert_eq!(stats.codec, Some(Codec::Vp8));
assert!(stats.error.is_none(), "{stats:?}");
let sent = streamer.stats();
// The encoder counts a frame once the sink has taken it, so the picture
// can be at the viewer before the count has moved.
let mut sent = streamer.stats();
for _ in 0..500 {
if sent.video_frames >= 15 && sent.audio_frames > 0 {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
sent = streamer.stats();
}
assert!(sent.video_frames >= 15 && sent.audio_frames > 0, "{sent:?}");
handles[0].send(StreamCmd::Stop);
@@ -331,4 +331,301 @@ mod tests {
let p = presence_from_book(&book, None, |_| false);
assert_eq!(avatar(&p, 6).as_deref(), Some("https://a.example/off.png"));
}
// ---- across the session seam ---------------------------------------------
/// A presence made into the entities the TeamSpeak session writes
/// (`ts_session::entities`), pushed the way a host syncs them, and
/// projected back by the engine (`link::project`): what the UI is shown
/// of what a TeamSpeak link reported (`docs/session-seam.md` section 5.1).
fn through_the_seam(presence: &Presence, ts6: bool, own: Option<u16>) -> Presence {
use voelin_model::replica::{Replica, SCHEMA_GENERATION, ScopeId};
use voelin_proto::link::Features;
use voelin_proto::v1::{self, push::Body};
use crate::link::media::TalkTracker;
use crate::link::project::{View, presence as project};
use crate::ts::ts_session::entities::build;
let built = build(presence, ts6, own);
let mut replica = Replica::new(SCHEMA_GENERATION);
for (scope, layer) in [(ScopeId::Server(1), &built.server), (ScopeId::Live(1), &built.live)]
{
replica.subscribe(scope);
let pushes = [
Body::SyncBegin(v1::SyncBegin {
scope: Some(scope.to_proto()),
mode: v1::SyncMode::Full as i32,
epoch: 1,
}),
Body::Change(v1::Change {
scope: Some(scope.to_proto()),
rev: 1,
put: layer.values().cloned().collect(),
del: Vec::new(),
}),
Body::SyncEnd(v1::SyncEnd {
scope: Some(scope.to_proto()),
cursor: Some(v1::Cursor { epoch: 1, rev: 1 }),
gap: false,
}),
];
for body in pushes {
replica.apply_push(&v1::Push { body: Some(body) });
}
}
let features = Features::new(["voice"]);
let talking = TalkTracker::default();
project(&View {
replica: &replica,
server: 1,
teamspeak: true,
version: "",
features: &features,
streams: ts6,
talking: &talking,
})
}
/// A TeamSpeak 6 server and some clients with what the book holds of them.
fn ts6_presence() -> Presence {
let mut book = ts6_book();
let list = format!(
"channellist {}|{}|{}",
channel(1, 0, "Lobby", "channel_banner_gfx_url channel_banner_mode=0"),
channel(
12,
1,
"Raid",
r"channel_banner_gfx_url=http:\/\/127.0.0.1:1\/d.png channel_banner_mode=2"
),
channel(20, 12, "Last", "channel_banner_gfx_url channel_banner_mode=0"),
);
book.handle_command(&message(&list)).unwrap();
let enter = |clid: u16, channel: u64, groups: &str, away: &str, avatar: &str| {
format!(
"notifycliententerview reasonid=0 ctid={channel} clid={clid} \
client_database_id={} client_nickname=c{clid} client_type=0 cfid=0 \
client_unique_identifier=u{clid}= client_flag_avatar=abcdef \
client_description=about\\sme client_icon_id=777 client_input_muted=1 \
client_output_muted=0 client_outputonly_muted=0 client_input_hardware=1 \
client_output_hardware=1 client_meta_data client_is_recording=1 \
client_channel_group_id=8 client_channel_group_inherited_channel_id=1 \
client_servergroups={groups} client_away={} client_away_message={away} \
client_talk_power=75 client_talk_request=0 client_talk_request_msg \
client_is_talker=1 client_is_priority_speaker=1 client_unread_messages=0 \
client_nickname_phonetic client_needed_serverquery_view_power=75 \
client_is_channel_commander=1 client_country=RU client_badges \
client_myteamspeak_id=m{clid} client_integrations{avatar}",
100 + u64::from(clid),
u8::from(!away.is_empty()),
)
};
for text in [
enter(5, 1, "8", "", r" client_myteamspeak_avatar=2,https:\/\/a.example\/on.png"),
enter(6, 12, "8,9", "gone\\sfishing", ""),
enter(7, 12, "", "", " client_myteamspeak_avatar"),
] {
book.handle_command(&message(&text)).unwrap();
}
presence_from_book(&book, Some("ibhejBRSRRI7v+fSsUzpQ33JGK6rf5xKOLelpWUr0sE="), |_| false)
}
#[test]
fn a_book_is_what_the_ui_is_shown_across_the_seam() {
let p = ts6_presence();
assert_eq!(p.clients.len(), 3, "the fixture has clients");
assert!(p.clients.values().any(|c| c.away.is_some()), "one is away");
// A TeamSpeak 6 client the book has no streaming flag of (it was not
// sent) is not streaming: v1 has no "unknown" for it.
let mut expected = p.clone();
for client in expected.clients.values_mut() {
client.streaming = Some(client.streaming.unwrap_or(false));
}
assert_eq!(through_the_seam(&p, true, Some(5)), expected);
// The same server as a TeamSpeak 3 one has no streams to tell of.
let mut ts3 = p.clone();
for client in ts3.clients.values_mut() {
client.streaming = None;
}
assert_eq!(through_the_seam(&ts3, false, Some(5)), ts3);
}
/// A deterministic stream of numbers for the generated presences.
struct Numbers(u64);
impl Numbers {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
fn flag(&mut self) -> bool {
self.below(2) == 0
}
fn text(&mut self, prefix: &str) -> String {
format!("{prefix}{}", self.below(1000))
}
}
/// A presence of the shape a TeamSpeak link reports: sibling channels in an
/// order chain, every client with a database id, unique ids that are base64
/// (TeamSpeak 3 and 6) or login names, groups of both kinds.
fn generated(seed: u64, ts6: bool) -> Presence {
use base64::Engine as _;
use voelin_model::{
BannerMode, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
HostMessageMode,
};
let mut n = Numbers(seed | 1);
let mut p = Presence::default();
let name = n.text("Server ");
p.server_name = name.clone();
p.server = voelin_model::ServerDetails {
name,
uid: Some(n.text("uid")),
welcome_message: n.text("welcome "),
host_message: n.text("host "),
host_message_mode: [
HostMessageMode::None,
HostMessageMode::Log,
HostMessageMode::Modal,
][n.below(3) as usize],
banner_url: if n.flag() { n.text("https://b/") } else { String::new() },
banner_gfx_url: if n.flag() { n.text("https://g/") } else { String::new() },
banner_gfx_interval_s: n.below(100),
banner_mode: [BannerMode::NoAdjust, BannerMode::IgnoreAspect, BannerMode::KeepAspect]
[n.below(3) as usize],
host_button_tooltip: if n.flag() { n.text("tip ") } else { String::new() },
host_button_url: String::new(),
host_button_gfx_url: String::new(),
icon: n.below(5) as u32 * 1000,
platform: "Linux".into(),
version: n.text("6.0."),
max_clients: n.below(500) as u16,
priority_speaker_dimm_db: -(n.below(30) as i32),
default_server_group: Some(1 + n.below(9)),
default_channel_group: Some(1 + n.below(9)),
};
// Groups.
for id in 1..=(2 + n.below(4)) {
let group = |id: u64, n: &mut Numbers| GroupInfo {
id,
name: n.text("group "),
icon: n.below(3) as u32 * 100,
sort_id: n.below(1000) as i32 - 500,
naming_mode: [
GroupNamingMode::None,
GroupNamingMode::Before,
GroupNamingMode::After,
][n.below(3) as usize],
group_type: [GroupType::Regular, GroupType::Template, GroupType::Query]
[n.below(3) as usize],
};
p.server_groups.insert(id, group(id, &mut n));
p.channel_groups.insert(id, group(id, &mut n));
}
// Channels: a tree whose siblings follow each other.
let mut parents = vec![0u64];
for id in 1..=(3 + n.below(8)) {
let parent = parents[n.below(parents.len() as u64) as usize];
let order = p
.channels
.values()
.filter(|c| c.parent == parent)
.map(|c| c.id)
.next_back()
.unwrap_or(0);
parents.push(id);
p.channels.insert(
id,
ChannelInfo {
id,
parent,
order,
name: n.text("channel "),
topic: n.flag().then(|| n.text("topic ")),
has_password: n.flag(),
max_clients: match n.below(3) {
0 => None,
1 => Some(0),
_ => Some(1 + n.below(50) as i32),
},
needed_subscribe_power: n.below(3) as i32 * 10,
needed_talk_power: n.below(3) as i32 * 25,
is_default: id == 1,
icon: n.below(3) as u32 * 500,
banner_gfx_url: n.flag().then(|| n.text("https://c/")),
banner_mode: [
BannerMode::NoAdjust,
BannerMode::IgnoreAspect,
BannerMode::KeepAspect,
][n.below(3) as usize],
},
);
}
// Clients.
let channels: Vec<u64> = p.channels.keys().copied().collect();
for id in 1..=(1 + n.below(12)) {
let id = id as u16;
let uid = match n.below(4) {
0 => None,
1 => Some(n.text("login")),
_ => {
let bytes: Vec<u8> =
(0..if ts6 { 32 } else { 20 }).map(|_| n.below(256) as u8).collect();
Some(base64::engine::general_purpose::STANDARD.encode(bytes))
}
};
let channel = channels[n.below(channels.len() as u64) as usize];
p.clients.insert(
id,
ClientInfo {
id,
uid,
nickname: n.text("nick "),
channel,
is_query: n.below(5) == 0,
away: n.flag().then(|| if n.flag() { n.text("away ") } else { String::new() }),
input_muted: n.flag(),
output_muted: n.flag(),
talking: Some(false),
streaming: ts6.then(|| n.flag()),
server_groups: (0..n.below(3)).map(|_| 1 + n.below(9)).collect(),
country: n.flag().then(|| "DE".into()),
avatar: n.flag().then(|| n.text("hash")),
myts_avatar: n.flag().then(|| n.text("https://a/")),
description: n.flag().then(|| n.text("about ")),
talk_power: n.below(100) as i32,
talker: n.flag(),
channel_group: n.flag().then(|| 1 + n.below(9)),
badges: (0..n.below(3)).map(|_| n.text("badge")).collect(),
icon: n.below(3) as u32 * 111,
recording: n.flag(),
priority_speaker: n.flag(),
channel_commander: n.flag(),
database_id: Some(1_000 + u64::from(id)),
},
);
}
p
}
#[test]
fn generated_presences_survive_the_seam() {
for seed in 1..=200u64 {
for ts6 in [false, true] {
let p = generated(seed.wrapping_mul(0x9e37_79b9_7f4a_7c15), ts6);
let own = p.clients.keys().next().copied();
assert_eq!(through_the_seam(&p, ts6, own), p, "seed {seed}, ts6 {ts6}");
}
}
}
}
@@ -32,6 +32,7 @@ use std::{fs, str};
use rusqlite::{Connection, OpenFlags, OptionalExtension};
use tsclientlib::Identity;
use voelin_gateway_proto::UniqueIds;
use voelin_identity::IdentityBlob;
use voelin_store::{IdentityOrigin, Store};
/// Name given to an identity whose source kept none.
@@ -55,6 +56,9 @@ pub enum IdentityError {
NoIdentity { path: String },
#[error("client database: {0}")]
Store(String),
/// An [`IdentityBlob`] that is no TeamSpeak identity ([`from_blob`]).
#[error("{0}")]
Blob(String),
}
impl IdentityError {
@@ -230,6 +234,77 @@ pub fn import_new(store: &Store, paths: &[PathBuf]) -> Result<LaunchImport, Iden
Ok(report)
}
/// A TeamSpeak identity as the API takes it
/// ([`VoiceOptions::identity`](crate::VoiceOptions::identity),
/// [`Command::ObserveGateway`](crate::Command::ObserveGateway)) and the key
/// store keeps it: kind `teamspeak`, the unique id TeamSpeak 3 servers know it
/// by (also how [`voelin_store`] keys it), its security level, and the JSON
/// the store writes.
pub fn to_blob(identity: &Identity) -> IdentityBlob {
// An identity is a key and two counters: writing it cannot fail. (A blob with
// no JSON is refused when it is used, in words.)
let json = serde_json::to_string(identity).unwrap_or_default();
IdentityBlob::teamspeak(identity.key().to_pub().get_uid(), identity.level(), json)
}
/// The TeamSpeak identity of a blob (the reverse of [`to_blob`]).
pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
if !blob.is_teamspeak() {
return Err(IdentityError::Blob(format!(
"the identity is of kind {:?}, not a TeamSpeak one",
blob.kind
)));
}
from_json(&blob.json)
}
/// The TeamSpeak identity in `json`, the text [`to_blob`] writes and the key
/// store keeps; voelin-core reads that text only through here (voelin-store
/// parses it too, for its own checks of a stored row).
///
/// What does not read is refused in words that say how it is wrong
/// (malformed, cut short, not an identity, unreadable) and where (line and
/// column), and never what it holds: the text holds a private key, and the
/// message of the JSON reader quotes a value it refuses (`tsproto` reports a
/// key that does not import as an invalid value, the key string and all), so
/// that message is never shown, not in an error, an event or a log.
pub(crate) fn from_json(json: &str) -> Result<Identity, IdentityError> {
serde_json::from_str(json).map_err(|e| {
let what = match e.classify() {
serde_json::error::Category::Syntax => "malformed",
serde_json::error::Category::Eof => "cut short",
serde_json::error::Category::Data => "not an identity",
serde_json::error::Category::Io => "unreadable",
};
IdentityError::Blob(format!(
"the TeamSpeak identity cannot be read: {what} at line {}, column {}",
e.line(),
e.column()
))
})
}
/// The JSON of a fresh identity whose key lost its last two characters (a key
/// that does not import), and that cut key.
#[cfg(test)]
pub(crate) fn json_with_a_cut_key() -> (String, String) {
let mut json = serde_json::to_value(Identity::create()).unwrap();
let key = json["key"].as_str().unwrap().to_owned();
let cut = key[..key.len() - 2].to_owned();
json["key"] = cut.clone().into();
(json.to_string(), cut)
}
/// Fail if `text` holds any 8 characters in a row of `secret`.
#[cfg(test)]
pub(crate) fn assert_holds_no_piece_of(text: &str, secret: &str) {
assert!(secret.len() >= 8 && secret.is_ascii());
for piece in secret.as_bytes().windows(8) {
let piece = std::str::from_utf8(piece).unwrap();
assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key");
}
}
/// The TeamSpeak 3 `.ini` export of an identity, which the official client
/// and every other tool reads.
pub fn export(nickname: &str, identity: &Identity) -> String {
@@ -548,18 +623,69 @@ mod tests {
Identity::create()
}
/// The blob of an identity is how the key store keeps it, and reads back as
/// the same identity; what is no TeamSpeak identity is refused without
/// quoting its JSON.
#[test]
fn an_identity_goes_through_its_blob() {
let identity = synthetic();
let blob = to_blob(&identity);
assert!(blob.is_teamspeak());
assert_eq!(blob.uid, identity.key().to_pub().get_uid());
assert_eq!(blob.level, identity.level());
assert_eq!(blob.json, serde_json::to_string(&identity).unwrap());
let back = from_blob(&blob).unwrap();
assert_eq!(serde_json::to_value(&back).unwrap(), serde_json::to_value(&identity).unwrap());
// Another kind.
let other = IdentityBlob::new("voelin", "x", 0, blob.json.clone());
let error = from_blob(&other).unwrap_err().to_string();
assert!(error.contains("\"voelin\""), "{error}");
// Not an identity: the text says where, and nothing of what it holds.
for json in ["", "{", r#"{"key":"hunter2-key","counter":"hunter2"}"#, "[1]"] {
let error = from_blob(&IdentityBlob::teamspeak("x", 0, json)).unwrap_err().to_string();
assert!(error.starts_with("the TeamSpeak identity cannot be read"), "{error}");
assert!(!error.contains("hunter2"), "{error}");
}
}
/// The JSON reader's own message quotes a key that does not import, so the
/// refusal is worded by `from_json` and holds none of the key.
#[test]
fn a_key_that_does_not_import_is_refused_without_quoting_it() {
let (json, cut) = json_with_a_cut_key();
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
assert!(raw.contains(&cut), "the reader's own message quotes the key: {raw}");
for error in [
from_json(&json).unwrap_err().to_string(),
from_blob(&IdentityBlob::teamspeak("x", 8, json.clone())).unwrap_err().to_string(),
] {
assert!(
error.starts_with(
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{error}"
);
assert_holds_no_piece_of(&error, &cut);
}
}
#[test]
fn improve_level_keeps_the_key() {
let identity = synthetic();
// A fresh identity stops at the first counter whose level is 8 or more,
// and about one in 32 has 13 or more already, which `improve_level`
// returns as it is: ask for more than this one has, whatever it has.
let target = identity.level() + 3;
let levels = std::sync::Mutex::new(Vec::new());
let better = improve_level(&identity, 13, &AtomicBool::new(false), |l| {
let better = improve_level(&identity, target, &AtomicBool::new(false), |l| {
levels.lock().unwrap().push(l);
})
.unwrap();
assert!(better.level() >= 13);
assert!(better.level() >= target);
assert_eq!(better.key().to_pub().get_uid(), identity.key().to_pub().get_uid());
assert!(better.counter() > identity.counter());
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= 13));
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= target));
// Cancelled: nothing.
assert!(improve_level(&identity, 60, &AtomicBool::new(true), |_| {}).is_none());
// Already there: the same identity.
+30
View File
@@ -0,0 +1,30 @@
//! The TeamSpeak implementation of the session seam.
//!
//! Everything of the engine that is TeamSpeak's lives here, so that it can
//! leave this crate for the TeamSpeak gateway (`voelin-gateway-ts` of
//! VoelinGateWay) as one piece (`docs/session-seam.md`, H9):
//!
//! - `ts_link.rs` and `voice.rs` are the connection of `tsclientlib`
//! (chat, voice, files, pokes, offline messages, the stream task's
//! requests) with `book.rs`, its presence from the library's book;
//! - `ts_session/` makes a `voelin_proto::link::Session` of such a connection
//! ([`TsConnector`] is the `Connector` the engine registers for
//! `ts3server://` and `teamspeak://`);
//! - [`versions`] and [`identity`] are what a TeamSpeak client has to know
//! about itself: the signed compatibility versions it can claim, and the
//! identities (reading, importing from the official clients, the security
//! level).
//!
//! The TeamSpeak crates' types (`tsclientlib::Identity`, `Version`, ...) are
//! named in the public items of this module and nowhere else of the crate's
//! API.
mod book;
pub mod identity;
mod ts_link;
pub(crate) mod ts_session;
pub mod versions;
mod voice;
pub(crate) use ts_link::{ConnectOptions, ServerLink, TsLink};
pub use ts_session::TsConnector;
+256
View File
@@ -0,0 +1,256 @@
//! The inner link of the TeamSpeak side: [`ServerLink`], the trait that
//! [`TsLink`] implements, and the [`ConnectOptions`] it connects with.
//!
//! The engine does not know this vocabulary: it talks to a
//! `voelin_proto::link::Session`. The `ts_session` module makes a `Session`
//! of a [`ServerLink`] (`LinkSession`), and the engine's tests give it a link
//! of their own, an in-memory one. [`TsLink`] connects as a normal TeamSpeak 3
//! or 6 client with `tsclientlib` and
//! runs the connection ([`super::voice`]) with everything that rides on it:
//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the
//! stream task. Which product the server is (and what it can do) is decided
//! there, from the version it sends, and reported in
//! [`LinkEvent::Connected`](crate::link::LinkEvent::Connected).
//!
//! Everything it uses (`voice.rs`, `book.rs`, `stream.rs`, `versions.rs`,
//! `identity.rs`) is TeamSpeak's and leaves this crate together with it:
//! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts`
//! of VoelinGateWay.
use std::sync::Arc;
use tokio::sync::{mpsc, watch};
use voelin_stream::PeerConfig;
use super::voice;
use crate::link::{LinkCmd, LinkCtx, LinkEvent};
/// Starts the connection of a link: the contract of `crate::link` for the
/// vocabulary ([`LinkCmd`] in, [`LinkEvent`] out) holds for what a link does
/// with them, and the module documentation of `link/session_link.rs` states
/// it.
///
/// One link serves every session of an engine; [`spawn`](Self::spawn) starts
/// one connection.
pub(crate) trait ServerLink: Send + Sync + 'static {
/// Connect to the server `options` names and run the connection on its
/// own task: take commands from `cmds`, report through `events`, and end
/// the connection with [`LinkEvent::Disconnected`]. Does not block.
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
);
}
/// What a TeamSpeak connection needs to know: the server, who to be, where
/// to join. The reverse of what the engine's `ConnectParams` carry
/// (`ts_session::inner_options`).
#[derive(Clone, Debug)]
pub(crate) struct ConnectOptions {
pub address: String,
pub nickname: String,
/// The identity to connect with; none generates one.
pub identity: Option<tsclientlib::Identity>,
/// Signed compatibility version; `None` selects the native platform's tuple.
pub client_version: Option<tsclientlib::Version>,
pub server_password: Option<String>,
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
pub channel: Option<String>,
/// The password of `channel`.
pub channel_password: Option<String>,
/// A privilege key to use when connecting.
pub token: Option<String>,
/// Open the audio devices (capture and playback).
pub audio: bool,
/// Network settings for stream peer connections.
pub stream_peer: PeerConfig,
}
impl ConnectOptions {
/// Options for `address` and `nickname`, the rest as a test leaves it.
#[cfg(test)]
pub(crate) fn new(address: impl Into<String>, nickname: impl Into<String>) -> Self {
Self {
address: address.into(),
nickname: nickname.into(),
identity: None,
client_version: None,
server_password: None,
channel: None,
channel_password: None,
token: None,
audio: false,
stream_peer: PeerConfig::default(),
}
}
}
/// The main myTeamSpeak account of an application, as its connections show
/// it to the servers: the proof of the myTS ID, and what servers are shown
/// of it (its avatar and badges with their certificates, its User Tag).
///
/// The senders live here, one pair for every connection of a [`TsLink`]; each
/// connection watches the pair through [`Watches`], presents the account it
/// finds when it connects, and follows the changes.
pub(crate) struct Account {
identity: watch::Sender<Option<Arc<tsproto::myts::Identity>>>,
data: watch::Sender<Option<Arc<tsclientlib::MytsData>>>,
}
impl Default for Account {
/// No account is signed in.
fn default() -> Self {
Self { identity: watch::Sender::new(None), data: watch::Sender::new(None) }
}
}
impl Account {
/// The account proof for every current and future connection. Still no
/// account is no change: every notification restarts the handshakes and
/// sends `updatemytsid` on every connection. Any account is (each
/// connection's proof is signed anew).
pub(crate) fn set_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
self.identity.send_if_modified(|current| {
if current.is_none() && identity.is_none() {
return false;
}
*current = identity;
true
});
}
/// What the servers are shown of the account: sent to every connection
/// that presents the account's myTS ID, once connected and when it
/// changes; cleared on a sign-out. The same data is no change.
pub(crate) fn set_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
self.data.send_if_modified(|current| {
if *current == data {
return false;
}
*current = data;
true
});
}
/// What one connection watches. It keeps the senders alive for as long as
/// it runs: a connection ends with "account source closed" when its
/// watches have lost them, so the account outlives the connector that
/// made the connection.
pub(crate) fn watches(self: &Arc<Self>) -> Watches {
Watches {
identity: self.identity.subscribe(),
data: self.data.subscribe(),
_keep: Some(self.clone()),
}
}
}
/// The account a connection presents and follows ([`Account::watches`]).
pub(crate) struct Watches {
pub(super) identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
pub(super) data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
_keep: Option<Arc<Account>>,
}
impl Watches {
/// Watches of senders that someone else keeps (a test's).
#[cfg(test)]
pub(super) fn of(
identity: watch::Receiver<Option<Arc<tsproto::myts::Identity>>>,
data: watch::Receiver<Option<Arc<tsclientlib::MytsData>>>,
) -> Self {
Self { identity, data, _keep: None }
}
}
/// Connects to TeamSpeak 3 and 6 servers. The link of [`TsConnector`](super::TsConnector).
#[derive(Clone, Default)]
pub(crate) struct TsLink {
account: Arc<Account>,
}
impl TsLink {
/// A link that presents no account until it is given one.
pub(crate) fn new() -> Self {
Self::default()
}
/// The account the link's connections present.
pub(crate) fn account(&self) -> &Arc<Account> {
&self.account
}
}
impl ServerLink for TsLink {
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
tokio::spawn(voice::run(options, ctx, self.account.watches(), cmds, events));
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A myTS ID's proof (the standard Ed25519 base point as the public key).
fn identity() -> Arc<tsproto::myts::Identity> {
let mut private = [0; 32];
private[0] = 1;
let mut public = [0x66; 32];
public[0] = 0x58;
Arc::new(
tsproto::myts::Identity::new(vec![1; 33], 42, public, private, vec![2; 65]).unwrap(),
)
}
/// An account sets what it holds only when it changes: every notification
/// of a watch restarts the handshake of a connection.
#[test]
fn a_watch_hears_of_a_change_and_not_of_the_same_account_again() {
let account = Arc::new(Account::default());
let mut watches = account.watches();
// No account, still none: nothing.
account.set_identity(None);
account.set_data(None);
assert!(!watches.identity.has_changed().unwrap());
assert!(!watches.data.has_changed().unwrap());
let proof = identity();
account.set_identity(Some(proof.clone()));
assert!(watches.identity.borrow_and_update().is_some());
// An account again is a change (each connection signs its proof anew), the
// same data is none.
account.set_identity(Some(proof));
assert!(watches.identity.has_changed().unwrap());
watches.identity.borrow_and_update();
let data = Arc::new(tsclientlib::MytsData::default());
account.set_data(Some(data.clone()));
assert!(watches.data.has_changed().unwrap());
watches.data.borrow_and_update();
account.set_data(Some(Arc::new(tsclientlib::MytsData::default())));
assert!(!watches.data.has_changed().unwrap(), "equal data is no change");
// A sign-out is a change.
account.set_identity(None);
assert!(watches.identity.has_changed().unwrap());
assert!(watches.identity.borrow_and_update().is_none());
}
/// A connection outlives the connector that made it (a session handed out
/// by a connector that was dropped): its watches keep their senders.
#[test]
fn a_connection_keeps_the_account_open_when_its_link_is_gone() {
let link = TsLink::new();
let watches = link.account().watches();
drop(link);
assert!(watches.identity.has_changed().is_ok(), "the identity watch lost its sender");
assert!(watches.data.has_changed().is_ok(), "the data watch lost its sender");
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,537 @@
//! The TeamSpeak connection's presence as v1 entities (protocol section
//! 11.1, "Ids and entities"): the client's older model on one side, the
//! protocol's `Server`, `Channel`, `Role`, `User`, `Member`, `Presence` and
//! `VoiceState` on the other.
//!
//! [`build`] is the translation the TeamSpeak `Session` makes of every
//! snapshot its link reports; the engine's projection (`link/project.rs`)
//! is its reverse, and `docs/session-seam.md` section 5.1 states the rule
//! both keep: projecting what was built gives back the snapshot (up to the
//! normalisations of section 5.4). What v1 has no field for rides in
//! [`Foreign`](v1::Foreign) under [`FOREIGN_SYSTEM`].
use std::collections::{BTreeMap, HashMap, HashSet};
use serde_json::json;
use voelin_model::replica::Key;
use voelin_model::{
BannerMode, ChannelId, ChannelInfo, ClientInfo, GroupInfo, GroupNamingMode, GroupType,
HostMessageMode, Presence, ServerDetails,
};
use voelin_proto::v1::{self, Entity, entity::Kind};
use super::ids::{self, FOREIGN_SYSTEM, SERVER_CHAT, SERVER_ID};
/// Entities by key, as a scope holds them.
pub(crate) type Layer = BTreeMap<Key, Entity>;
/// The entities one snapshot stands for, by scope.
#[derive(Debug, Default)]
pub(crate) struct Built {
/// SERVER (1): the server, its channels and its roles.
pub server: Layer,
/// LIVE (1): who is online and where.
pub live: Layer,
/// The own user, for HOME, when the snapshot holds our client.
pub own_user: Option<v1::User>,
/// Clients by unique id: their user id and participant id.
pub by_uid: HashMap<String, (u64, u32)>,
}
/// The `Foreign` of something v1 has no field for.
pub(crate) fn foreign(kind: &str, json: &serde_json::Value) -> v1::Foreign {
v1::Foreign {
system: FOREIGN_SYSTEM.into(),
kind: kind.into(),
json: serde_json::to_vec(json).unwrap_or_default().into(),
}
}
fn entity(kind: Kind) -> Entity {
Entity { kind: Some(kind) }
}
/// A picture known by its id (an icon CRC).
fn icon(id: u32) -> Option<v1::Image> {
(id != 0).then(|| v1::Image { hash: id.to_string(), ..Default::default() })
}
fn banner_mode(mode: BannerMode) -> v1::BannerMode {
match mode {
BannerMode::NoAdjust => v1::BannerMode::NoAdjust,
BannerMode::IgnoreAspect => v1::BannerMode::IgnoreAspect,
BannerMode::KeepAspect => v1::BannerMode::KeepAspect,
}
}
fn host_message_mode(mode: HostMessageMode) -> v1::HostMessageMode {
match mode {
HostMessageMode::None => v1::HostMessageMode::None,
HostMessageMode::Log => v1::HostMessageMode::Log,
HostMessageMode::Modal => v1::HostMessageMode::Modal,
HostMessageMode::ModalQuit => v1::HostMessageMode::ModalQuit,
}
}
/// The `Server` entity of a connection.
pub(crate) fn server(details: &ServerDetails, name: &str, default_channel: u64) -> v1::Server {
let gfx =
|url: &str| (!url.is_empty()).then(|| v1::Image { url: url.into(), ..Default::default() });
let banner = (!details.banner_url.is_empty()
|| !details.banner_gfx_url.is_empty()
|| details.banner_gfx_interval_s != 0
|| details.banner_mode != BannerMode::NoAdjust)
.then(|| v1::Banner {
image: gfx(&details.banner_gfx_url),
link: details.banner_url.clone(),
reload_s: u32::try_from(details.banner_gfx_interval_s).unwrap_or(u32::MAX),
mode: banner_mode(details.banner_mode) as i32,
});
let host_button = (!details.host_button_tooltip.is_empty()
|| !details.host_button_url.is_empty()
|| !details.host_button_gfx_url.is_empty())
.then(|| v1::HostButton {
tooltip: details.host_button_tooltip.clone(),
url: details.host_button_url.clone(),
icon: gfx(&details.host_button_gfx_url),
});
v1::Server {
id: SERVER_ID,
name: name.to_owned(),
icon: icon(details.icon),
banner,
host_button,
welcome: details.welcome_message.clone(),
host_message: details.host_message.clone(),
host_message_mode: host_message_mode(details.host_message_mode) as i32,
default_channel_id: default_channel,
default_role_id: details.default_server_group.unwrap_or(0),
default_channel_role_id: details.default_channel_group.map_or(0, ids::channel_role),
priority_dim_db: details.priority_speaker_dimm_db,
max_members: u32::from(details.max_clients),
uid: details.uid.as_deref().map(|uid| format!("ts:{uid}")).unwrap_or_default(),
foreign: Some(foreign(
"server",
&json!({ "platform": details.platform, "version": details.version }),
)),
..Default::default()
}
}
/// The server group or channel group `info` as a role.
fn role(info: &GroupInfo, channel: bool) -> v1::Role {
v1::Role {
id: if channel { ids::channel_role(info.id) } else { info.id },
server_id: SERVER_ID,
name: info.name.clone(),
icon: icon(info.icon),
position: info.sort_id.saturating_neg(),
scope: if channel { v1::RoleScope::Channel } else { v1::RoleScope::Server } as i32,
name_mode: match info.naming_mode {
GroupNamingMode::None => v1::NameMode::None,
GroupNamingMode::Before => v1::NameMode::Before,
GroupNamingMode::After => v1::NameMode::After,
} as i32,
kind: match info.group_type {
GroupType::Template => v1::RoleKind::Template,
GroupType::Regular => v1::RoleKind::Regular,
GroupType::Query => v1::RoleKind::Query,
} as i32,
..Default::default()
}
}
/// The sibling chain of each parent as positions: `order` names the sibling
/// above, so the chain is followed from 0; siblings that no chain reaches
/// (a snapshot with broken orders) follow by id.
fn positions(channels: &BTreeMap<ChannelId, ChannelInfo>) -> HashMap<ChannelId, i64> {
let mut by_parent: BTreeMap<ChannelId, Vec<&ChannelInfo>> = BTreeMap::new();
for channel in channels.values() {
by_parent.entry(channel.parent).or_default().push(channel);
}
let mut positions = HashMap::new();
for siblings in by_parent.values() {
let mut placed: HashSet<ChannelId> = HashSet::new();
let mut next = 0;
let mut above = 0;
// The sibling whose `order` is the one placed last (lowest id first, so
// that two claiming the same place do not depend on map order).
while let Some(channel) = siblings
.iter()
.filter(|c| c.order == above && !placed.contains(&c.id))
.min_by_key(|c| c.id)
{
positions.insert(channel.id, next * 1024);
placed.insert(channel.id);
above = channel.id;
next += 1;
}
for channel in siblings.iter().filter(|c| !placed.contains(&c.id)) {
positions.insert(channel.id, next * 1024);
next += 1;
}
}
positions
}
fn channel(info: &ChannelInfo, position: i64) -> v1::Channel {
let mut needed = HashMap::new();
if info.needed_talk_power != 0 {
needed.insert(v1::Power::Talk as u32, info.needed_talk_power);
}
if info.needed_subscribe_power != 0 {
needed.insert(v1::Power::Subscribe as u32, info.needed_subscribe_power);
}
let banner =
(info.banner_gfx_url.is_some() || info.banner_mode != BannerMode::NoAdjust).then(|| {
v1::Banner {
image: info
.banner_gfx_url
.as_ref()
.map(|url| v1::Image { url: url.clone(), ..Default::default() }),
mode: banner_mode(info.banner_mode) as i32,
..Default::default()
}
});
v1::Channel {
id: info.id,
server_id: SERVER_ID,
parent_id: info.parent,
kind: v1::ChannelKind::Voice as i32,
name: info.name.clone(),
topic: info.topic.clone().unwrap_or_default(),
position,
has_password: info.has_password,
// A limit of 0 cannot be said with `max_members` (0 is unlimited).
max_members: info.max_clients.map_or(0, |n| u32::try_from(n).unwrap_or(0)),
needed,
icon: icon(info.icon),
banner,
is_default: info.is_default,
foreign: (info.max_clients == Some(0))
.then(|| foreign("channel", &json!({ "max_clients": 0 }))),
..Default::default()
}
}
/// The user a client is. `Foreign` carries a unique id that is no base64.
fn user(client: &ClientInfo, id: u64, ts6: bool) -> v1::User {
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
let bytes = uid.and_then(ids::uid_bytes);
let avatar = (client.avatar.is_some() || client.myts_avatar.is_some()).then(|| v1::Image {
hash: client.avatar.clone().unwrap_or_default(),
url: client.myts_avatar.clone().unwrap_or_default(),
..Default::default()
});
v1::User {
id,
uid: bytes.clone().unwrap_or_default().into(),
uid_kind: if ts6 { v1::IdKind::Ts6 } else { v1::IdKind::Ts3 } as i32,
name: client.nickname.clone(),
avatar,
badges: client.badges.clone(),
country: client.country.clone().unwrap_or_default(),
foreign: uid.filter(|_| bytes.is_none()).map(|uid| foreign("user", &json!({ "uid": uid }))),
..Default::default()
}
}
/// A user who is on no snapshot (the sender of a message or a poke): its
/// unique id and name only. `None` for a unique id with no content.
pub(crate) fn bare_user(uid: &str, name: &str, ts6: bool) -> v1::User {
user(
&ClientInfo { uid: Some(uid.to_owned()), nickname: name.to_owned(), ..Default::default() },
ids::synthetic_user(uid),
ts6,
)
}
/// A user who is on no snapshot and has no unique id (the sender of a poke
/// or a message that the link names by its client id only): `id` and name.
pub(crate) fn client_user(id: u64, name: &str, ts6: bool) -> v1::User {
user(&ClientInfo { nickname: name.to_owned(), ..Default::default() }, id, ts6)
}
/// Everything the snapshot `presence` says, as entities of the scopes of
/// server 1. `ts6`: the server is TeamSpeak 6 (the kind of its unique ids).
pub(crate) fn build(presence: &Presence, ts6: bool, own_client: Option<u16>) -> Built {
let mut built = Built::default();
let name =
if presence.server.name.is_empty() { &presence.server_name } else { &presence.server.name };
let default_channel =
presence.channels.values().find(|c| c.is_default).map_or(0, |channel| channel.id);
let put = |layer: &mut Layer, kind: Kind| {
let entity = entity(kind);
if let Some(key) = Key::of(&entity) {
layer.insert(key, entity);
}
};
put(&mut built.server, Kind::Server(server(&presence.server, name, default_channel)));
put(
&mut built.server,
Kind::Channel(v1::Channel {
id: SERVER_CHAT,
server_id: SERVER_ID,
kind: v1::ChannelKind::ServerChat as i32,
name: "Server chat".into(),
..Default::default()
}),
);
let positions = positions(&presence.channels);
for info in presence.channels.values() {
let position = positions.get(&info.id).copied().unwrap_or_default();
put(&mut built.server, Kind::Channel(channel(info, position)));
}
for info in presence.server_groups.values() {
put(&mut built.server, Kind::Role(role(info, false)));
}
for info in presence.channel_groups.values() {
put(&mut built.server, Kind::Role(role(info, true)));
}
// The own client first, then by client id.
let mut clients: Vec<&ClientInfo> = presence.clients.values().collect();
clients.sort_by_key(|client| (Some(client.id) != own_client, client.id));
let mut used: HashSet<u64> = HashSet::new();
for client in clients {
// The same identity twice on a server has one database id: the own
// client keeps it (it must stay the user we are, also while a ghost of
// our old connection lingers), else the lower client id; the other is a
// user of its own.
let uid = client.uid.as_deref().filter(|u| !u.is_empty());
let mut id = client.database_id.unwrap_or_else(|| {
ids::synthetic_user(&uid.map_or_else(|| format!("client:{}", client.id), str::to_owned))
});
if !used.insert(id) {
id = ids::synthetic_user(&format!("client:{}", client.id));
used.insert(id);
}
let participant = u32::from(client.id);
if let Some(uid) = uid {
built.by_uid.entry(uid.to_owned()).or_insert((id, participant));
}
let user = user(client, id, ts6);
if Some(client.id) == own_client {
built.own_user = Some(user.clone());
}
put(&mut built.live, Kind::User(user));
put(
&mut built.live,
Kind::Member(v1::Member {
server_id: SERVER_ID,
user_id: id,
roles: client.server_groups.clone(),
channel_roles: client
.channel_group
.map(|group| (client.channel, ids::channel_role(group)))
.into_iter()
.collect(),
description: client.description.clone().unwrap_or_default(),
foreign: (client.icon != 0)
.then(|| foreign("client", &json!({ "icon": client.icon }))),
..Default::default()
}),
);
put(
&mut built.live,
Kind::Presence(v1::Presence {
user_id: id,
status: if client.away.is_some() { v1::Status::Idle } else { v1::Status::Online }
as i32,
text: client.away.clone().unwrap_or_default(),
..Default::default()
}),
);
put(
&mut built.live,
Kind::Voice(v1::VoiceState {
server_id: SERVER_ID,
participant_id: participant,
user_id: id,
channel_id: client.channel,
slot: slot(client.id),
nick: client.nickname.clone(),
kind: if client.is_query {
v1::ParticipantKind::Query
} else {
v1::ParticipantKind::User
} as i32,
self_mute: client.input_muted,
self_deaf: client.output_muted,
priority_speaker: client.priority_speaker,
channel_commander: client.channel_commander,
talker: client.talker,
talk_power: client.talk_power,
recording: client.recording,
streaming: client.streaming.unwrap_or(false),
..Default::default()
}),
);
}
built
}
/// The unique id of a user as the client's older model writes it: base64 for
/// a TeamSpeak id, or the text kept in `Foreign` when it was no base64 (a
/// ServerQuery client's login name). `None` for a user without one.
pub(crate) fn user_uid(user: &v1::User) -> Option<String> {
let kept = user
.foreign
.as_ref()
.filter(|f| f.system == FOREIGN_SYSTEM && f.kind == "user")
.and_then(|f| serde_json::from_slice::<serde_json::Value>(&f.json).ok())
.and_then(|json| json.get("uid")?.as_str().map(str::to_owned));
kept.or_else(|| voelin_model::replica::convert::uid_text(user))
}
/// The media slot of a client: its id plus one (slot 0 is not a media source).
pub(crate) fn slot(client: u16) -> u32 {
u32::from(client) + 1
}
/// The key of an entity, as a `Change` deletes it: the key fields only.
pub(crate) fn key_only(entity: &Entity) -> Entity {
let kind = match entity.kind.as_ref() {
Some(Kind::Server(s)) => Kind::Server(v1::Server { id: s.id, ..Default::default() }),
Some(Kind::Channel(c)) => Kind::Channel(v1::Channel { id: c.id, ..Default::default() }),
Some(Kind::Role(r)) => {
Kind::Role(v1::Role { server_id: r.server_id, id: r.id, ..Default::default() })
}
Some(Kind::Member(m)) => Kind::Member(v1::Member {
server_id: m.server_id,
user_id: m.user_id,
..Default::default()
}),
Some(Kind::User(u)) => Kind::User(v1::User { id: u.id, ..Default::default() }),
Some(Kind::Presence(p)) => {
Kind::Presence(v1::Presence { user_id: p.user_id, ..Default::default() })
}
Some(Kind::Voice(v)) => Kind::Voice(v1::VoiceState {
server_id: v.server_id,
participant_id: v.participant_id,
..Default::default()
}),
Some(Kind::Message(m)) => {
Kind::Message(v1::Message { channel_id: m.channel_id, id: m.id, ..Default::default() })
}
Some(Kind::Mail(m)) => Kind::Mail(v1::Mail { id: m.id, ..Default::default() }),
_ => return entity.clone(),
};
Entity { kind: Some(kind) }
}
/// What changed from `old` to `new`: the entities to put (new or different)
/// and the keys to delete.
pub(crate) fn diff(old: &Layer, new: &Layer) -> (Vec<Entity>, Vec<Entity>) {
let put = new.iter().filter(|(key, entity)| old.get(*key) != Some(*entity));
let del = old.iter().filter(|(key, _)| !new.contains_key(*key));
(put.map(|(_, e)| e.clone()).collect(), del.map(|(_, e)| key_only(e)).collect())
}
#[cfg(test)]
mod tests {
use super::*;
fn channel_info(id: u64, parent: u64, order: u64) -> ChannelInfo {
ChannelInfo { id, parent, order, name: format!("c{id}"), ..Default::default() }
}
#[test]
fn the_order_chain_becomes_positions() {
// 3 first, then 1, then 2 under the same parent; 5 alone under 3.
let channels: BTreeMap<_, _> = [
channel_info(1, 0, 3),
channel_info(2, 0, 1),
channel_info(3, 0, 0),
channel_info(5, 3, 0),
]
.into_iter()
.map(|c| (c.id, c))
.collect();
let positions = positions(&channels);
assert!(positions[&3] < positions[&1] && positions[&1] < positions[&2]);
assert_eq!(positions[&5], 0);
}
#[test]
fn siblings_a_chain_does_not_reach_follow_by_id() {
// Both claim the first place, and 4 follows nobody.
let channels: BTreeMap<_, _> =
[channel_info(1, 0, 0), channel_info(2, 0, 0), channel_info(4, 0, 77)]
.into_iter()
.map(|c| (c.id, c))
.collect();
let positions = positions(&channels);
assert_eq!((positions[&1], positions[&2], positions[&4]), (0, 1024, 2048));
}
#[test]
fn the_same_identity_twice_keeps_both_clients() {
let client = |id, db| ClientInfo {
id,
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
nickname: format!("n{id}"),
database_id: Some(db),
..Default::default()
};
let mut presence = Presence::default();
for c in [client(3, 77), client(4, 77)] {
presence.clients.insert(c.id, c);
}
let built = build(&presence, false, None);
let voices = built.live.keys().filter(|k| matches!(k, Key::Voice { .. })).count();
let users = built.live.keys().filter(|k| matches!(k, Key::User { .. })).count();
assert_eq!((voices, users), (2, 2));
}
/// The own client is the user whose database id the identity has, also when a
/// ghost of the old connection (the lower client id) lingers.
#[test]
fn the_own_client_keeps_the_database_id_of_an_identity_that_is_there_twice() {
let client = |id| ClientInfo {
id,
uid: Some("uXDkxSZbv0IoA0z/toW3guGpUbI=".into()),
nickname: format!("n{id}"),
database_id: Some(77),
..Default::default()
};
let mut presence = Presence::default();
for c in [client(3), client(4)] {
presence.clients.insert(c.id, c);
}
let user_of = |built: &Built, client: u32| {
let key = Key::Voice { server_id: SERVER_ID, participant_id: client };
let Some(Entity { kind: Some(Kind::Voice(voice)) }) = built.live.get(&key) else {
panic!("no voice state")
};
voice.user_id
};
// Nobody is us: the lower client id keeps it.
let built = build(&presence, false, None);
assert_eq!(user_of(&built, 3), 77);
assert_ne!(user_of(&built, 4), 77);
// The later client is us: it keeps it, and the ghost has the made-up id.
let built = build(&presence, false, Some(4));
assert_eq!(user_of(&built, 4), 77);
assert_ne!(user_of(&built, 3), 77);
assert_eq!(built.own_user.map(|u| u.id), Some(77));
assert_eq!(built.by_uid["uXDkxSZbv0IoA0z/toW3guGpUbI="], (77, 4));
}
#[test]
fn a_change_deletes_by_key_and_puts_what_differs() {
let mut presence = Presence::default();
presence.channels.insert(1, channel_info(1, 0, 0));
let before = build(&presence, false, None);
presence.channels.insert(2, channel_info(2, 0, 1));
presence.channels.get_mut(&1).unwrap().name = "renamed".into();
let after = build(&presence, false, None);
let (put, del) = diff(&before.server, &after.server);
assert_eq!(put.len(), 2, "the renamed channel and the new one");
assert!(del.is_empty());
let (put, del) = diff(&after.server, &before.server);
assert_eq!(put.len(), 1, "channel 1 is back to its old name");
assert_eq!(del.len(), 1);
let Some(Kind::Channel(gone)) = &del[0].kind else { panic!("a channel") };
assert_eq!((gone.id, gone.name.as_str()), (2, ""));
}
}
+115
View File
@@ -0,0 +1,115 @@
//! Ids and unique ids as the TeamSpeak gateway writes them (protocol
//! section 11.1, "Ids"): TeamSpeak's numbers as they are, and a few
//! synthetic ones with bit 63 set.
//!
//! Both sides of the seam use these rules: the TeamSpeak `Session`
//! ([`super::LinkSession`]) writes entities with them, and the engine's
//! projection (`link/project.rs`) undoes the few that the client's older
//! model has no room for.
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
/// The only server of a TeamSpeak connection (its virtual server).
pub(crate) const SERVER_ID: u64 = 1;
/// Marks the ids the gateway makes up: the server chat, direct-message
/// channels and users it knows by their unique id only.
pub(crate) const SYNTHETIC: u64 = 1 << 63;
/// The channel of the server chat, in the SERVER scope.
pub(crate) const SERVER_CHAT: u64 = SYNTHETIC;
/// Set on the id of a channel group, so that a role id does not mean a server
/// group and a channel group at once.
pub(crate) const CHANNEL_ROLE: u64 = 1 << 62;
/// The `Foreign.system` of what the protocol has no field for.
pub(crate) const FOREIGN_SYSTEM: &str = "teamspeak";
/// The role id of a channel group.
pub(crate) fn channel_role(group: u64) -> u64 {
group | CHANNEL_ROLE
}
/// The channel group a role id stands for (the reverse of [`channel_role`]).
pub(crate) fn channel_group(role: u64) -> u64 {
role & !CHANNEL_ROLE
}
/// FNV-1a, 64 bits.
fn fnv1a(bytes: &[u8]) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}
/// A synthetic id for something known by a name only: bit 63 set and the
/// hash of `name` in the low 63 bits (1 if they come out 0, so it is never
/// [`SERVER_CHAT`]).
fn synthetic(name: &str) -> u64 {
let low = fnv1a(name.as_bytes()) & !SYNTHETIC;
SYNTHETIC | low.max(1)
}
/// The direct-message channel with the client of this unique id.
pub(crate) fn dm_channel(uid: &str) -> u64 {
synthetic(uid)
}
/// The user id of a client that has no database id (or that the snapshot
/// does not hold): by unique id, else by whatever names it.
pub(crate) fn synthetic_user(uid: &str) -> u64 {
synthetic(uid)
}
/// The bytes of a unique id, when it is canonical base64 (what TeamSpeak
/// writes): decoding and encoding again gives the same text. A ServerQuery
/// client's login name, or anything else, is not, and goes into
/// [`Foreign`](voelin_proto::v1::Foreign) instead.
pub(crate) fn uid_bytes(uid: &str) -> Option<Vec<u8>> {
let bytes = STANDARD.decode(uid).ok()?;
(STANDARD.encode(&bytes) == uid && !bytes.is_empty()).then_some(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn channel_groups_keep_their_number_below_the_flag() {
assert_eq!(channel_role(8), 8 | (1 << 62));
assert_eq!(channel_group(channel_role(8)), 8);
assert_eq!(channel_group(channel_role(0)), 0);
}
#[test]
fn synthetic_ids_have_bit_63_and_are_never_the_server_chat() {
for name in ["", "alice=", "client:7", "a-very-long-name-that-hashes-to-something"] {
let id = dm_channel(name);
assert_ne!(id & SYNTHETIC, 0, "{name}");
assert_ne!(id, SERVER_CHAT, "{name}");
}
assert_eq!(dm_channel("alice="), dm_channel("alice="));
assert_ne!(dm_channel("alice="), dm_channel("bob="));
}
#[test]
fn only_canonical_base64_is_a_unique_id() {
// A TeamSpeak 3 unique id (SHA-1) and a TeamSpeak 6 one (SHA-256).
assert_eq!(uid_bytes("uXDkxSZbv0IoA0z/toW3guGpUbI=").map(|b| b.len()), Some(20));
assert_eq!(
uid_bytes("xEZDkyeGdZ4bOSBCKqzTw8jVz2jsZCrJDRl9F8WWd3M=").map(|b| b.len()),
Some(32)
);
// A ServerQuery login name, a fixture's name, the empty string.
for not in ["serveradmin", "alice=", "me=", "", "Af4"] {
assert_eq!(uid_bytes(not), None, "{not:?}");
}
// Non-canonical trailing bits decode but do not round trip.
assert_eq!(uid_bytes("Af5="), None);
}
}
@@ -0,0 +1,862 @@
//! The TeamSpeak `Session` against the development servers
//! (`dev/docker-compose.yml`; `docs/session-seam.md` sections 9.3 and 16).
//! Runs only with `VOELIN_LIVE=1`:
//!
//! ```text
//! VOELIN_LIVE=1 cargo test -p voelin-core --lib ts_session::live_tests -- --test-threads=1
//! ```
//!
//! Two kinds of test, each on TeamSpeak 3 and on TeamSpeak 6:
//!
//! - the link conformance suite of the protocol repository, the cases that
//! apply to a TeamSpeak session, with the verdict of every case asserted
//! and the reason of every case that cannot pass or cannot run in
//! [`EXPECTED`];
//! - what the suite cannot reach, as a session of its own does it: a message
//! in the own channel answered, then pushed to the other session and back to
//! ours, the refusals of a move, a poke between two sessions, voice RTP from
//! one session's slot to the other's media sink, and a channel file written
//! and read back from an offset.
//!
//! The sessions are made by [`TsConnector`] through the plain `Connector`
//! interface, as a client of the seam outside an engine would make them.
//!
//! The servers ban an address that connects as often as these tests do
//! (`ConnectFailedBanned` after three or four connections) unless their
//! anti-flood limits are raised first. `scripts/it-smoke.sh` raises them when it
//! prepares its admin identity; this module raises them itself, once per server
//! and run, through the ServerQuery admin login that `refused_moves` uses
//! ([`raise_flood_limits`]), so that the command above works on a freshly
//! started stack. It needs that login (the development servers of
//! `dev/docker-compose.yml` have it) and does not lower the limits again.
use std::collections::BTreeMap;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::mpsc;
use voelin_proto::link::{Connector, FlowId, MediaClass, MediaPacket, voice_sub};
use voelin_proto::media::payload::PT_OPUS;
use voelin_proto::media::{RtpHeader, RtpView};
use voelin_proto::test_util::conformance::{self, Fixture, Verdict};
use voelin_proto::test_util::{FakeConnector, MediaReceiver, media_channel};
use voelin_proto::v1::request::Op;
use voelin_proto::v1::{self, entity::Kind};
use super::*;
use crate::link::{Backends, VoiceOptions, connect_params};
fn live() -> bool {
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
}
/// How long a test waits for the server.
const WAIT: Duration = Duration::from_secs(20);
async fn within<T>(what: &str, future: impl Future<Output = T>) -> T {
match tokio::time::timeout(WAIT, future).await {
Ok(value) => value,
Err(_) => panic!("timed out after {WAIT:?} waiting for {what}"),
}
}
/// A development server: where to connect, and how to ask it as the admin.
#[derive(Clone, Copy)]
struct Dev {
name: &'static str,
voice: &'static str,
ssh: bool,
query: &'static str,
}
const TS3: Dev = Dev { name: "ts3", voice: "127.0.0.1:9987", ssh: false, query: "127.0.0.1:10011" };
const TS6: Dev = Dev { name: "ts6", voice: "127.0.0.1:9988", ssh: true, query: "127.0.0.1:10022" };
impl Dev {
fn query(&self) -> voelin_query::Connect {
voelin_query::Connect {
transport: if self.ssh {
voelin_query::Transport::Ssh
} else {
voelin_query::Transport::Raw
},
addr: self.query.into(),
user: "serveradmin".into(),
secret: Some("voelin-dev-admin".into()),
server_port: Some(9987),
server_id: None,
line: voelin_query::LineOptions { rate_limit: None, ..Default::default() },
}
}
/// A nickname no other client of this run has.
fn nick(&self, role: &str) -> String {
static COUNT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let n = COUNT.fetch_add(1, Ordering::Relaxed);
format!("{role}-{}-{n}", std::process::id() % 10_000)
}
}
/// Raise the anti-flood limits of a development server, once per run, and
/// lift the bans an earlier run left behind. The tests connect many times in
/// a few seconds from one address, which a server with its default limits
/// bans (`ConnectFailedBanned`); `scripts/it-smoke.sh` sets the same two
/// values in `admin_args`. Done through the ServerQuery login of the admin,
/// which the tests that create channels and keys use as well.
async fn raise_flood_limits(dev: &Dev) {
use tokio::sync::OnceCell;
use voelin_query::{Command as Query, QueryClient};
static TS3_READY: OnceCell<()> = OnceCell::const_new();
static TS6_READY: OnceCell<()> = OnceCell::const_new();
let ready = if dev.ssh { &TS6_READY } else { &TS3_READY };
ready
.get_or_init(|| async {
let (admin, _) = within("the query login", QueryClient::connect(&dev.query()))
.await
.unwrap_or_else(|e| panic!("the query login of {}: {e}", dev.name));
for key in [
"virtualserver_antiflood_points_needed_ip_block",
"virtualserver_antiflood_points_needed_command_block",
] {
let edit = Query::new("serveredit").arg(key, 100_000);
within("the anti-flood limits", admin.send(&edit))
.await
.unwrap_or_else(|e| panic!("{} refused {key}: {e}", dev.name));
}
// A ban of an earlier run outlives the change of the limit.
within("the ban list", admin.send(&Query::new("bandelall")))
.await
.unwrap_or_else(|e| panic!("{} did not lift its bans: {e}", dev.name));
})
.await;
}
/// A TeamSpeak session as a client of the seam sees it: made by the
/// connector, with its push channel and media sink.
async fn session(
dev: &Dev,
options: &VoiceOptions,
) -> (Arc<dyn Session>, mpsc::Receiver<v1::Push>, MediaReceiver) {
raise_flood_limits(dev).await;
let (sink, media) = media_channel();
let params = connect_params(options, sink, &Backends::empty()).expect("connect parameters");
let connected =
within(&format!("a connection to {}", dev.name), TsConnector::new().connect(params))
.await
.unwrap_or_else(|e| panic!("{} did not connect: {e}", dev.name));
(connected.session, connected.pushes, media)
}
/// A client of the TeamSpeak session that has done what an engine does after
/// it connects (`docs/session-seam.md` 4.2, without the replica): the server
/// listed, HOME, SERVER and LIVE subscribed and synced, a seat in voice.
struct Client {
session: Arc<dyn Session>,
pushes: mpsc::Receiver<v1::Push>,
media: MediaReceiver,
server: u64,
default_channel: u64,
/// Our seat in voice (participant, slot, channel).
seat: v1::VoiceState,
/// The voice states of the server, as the pushes told them.
voices: BTreeMap<u32, v1::VoiceState>,
}
fn scope(kind: v1::ScopeKind, id: u64) -> v1::Scope {
v1::Scope { kind: kind as i32, id }
}
impl Client {
async fn connect(dev: &Dev, nick: &str) -> Self {
Self::connect_with(dev, VoiceOptions::new(dev.voice, nick)).await
}
async fn connect_with(dev: &Dev, options: VoiceOptions) -> Self {
let (session, pushes, media) = session(dev, &options).await;
let mut client = Self {
session,
pushes,
media,
server: 0,
default_channel: 0,
seat: v1::VoiceState::default(),
voices: BTreeMap::new(),
};
let list = Op::List(v1::List { kind: v1::EntityKind::Server as i32, ..Default::default() });
let Answer::Entities(servers) = client.ask(list).await.expect("the server list") else {
panic!("the server list is not entities")
};
let server = servers
.items
.iter()
.find_map(|e| match &e.kind {
Some(Kind::Server(server)) => Some(server.clone()),
_ => None,
})
.expect("the host lists its server");
client.server = server.id;
client.default_channel = server.default_channel_id;
for scope in [
scope(v1::ScopeKind::Home, 0),
scope(v1::ScopeKind::Server, server.id),
scope(v1::ScopeKind::Live, server.id),
] {
client.subscribe(scope).await;
}
client.seat = client.join(client.default_channel, "").await.expect("a seat in voice");
client.settle().await;
client
}
/// A request, answered within [`WAIT`].
async fn ask(&self, op: Op) -> Result<Answer, SessionError> {
within("an answer", self.session.request(op)).await
}
/// Subscribe `scope` and take its sync off the push channel.
async fn subscribe(&mut self, scope: v1::Scope) {
let op = Op::Subscribe(v1::Subscribe { scope: Some(scope), ..Default::default() });
self.ask(op).await.expect("a subscription");
self.until("the end of the sync", |push| match &push.body {
Some(v1::push::Body::SyncEnd(end)) if end.scope == Some(scope) => Some(()),
_ => None,
})
.await;
}
/// `JoinVoice`: our seat, or why not.
async fn join(&self, channel: u64, password: &str) -> Result<v1::VoiceState, SessionError> {
let join = v1::JoinVoice {
server_id: self.server,
channel_id: channel,
password: password.into(),
..Default::default()
};
match self.ask(Op::JoinVoice(join)).await? {
Answer::Entities(entities) => entities
.items
.into_iter()
.find_map(|e| match e.kind {
Some(Kind::Voice(voice)) => Some(voice),
_ => None,
})
.ok_or_else(|| SessionError::Protocol("no voice state in the answer".into())),
other => Err(SessionError::Protocol(format!("unexpected answer {other:?}"))),
}
}
/// Keep track of what a push says about the server and its voice states.
fn absorb(&mut self, push: &v1::Push) {
let Some(v1::push::Body::Change(change)) = &push.body else { return };
for entity in &change.put {
match &entity.kind {
Some(Kind::Voice(voice)) => {
self.voices.insert(voice.participant_id, voice.clone());
}
Some(Kind::Server(server)) if server.default_channel_id != 0 => {
self.default_channel = server.default_channel_id;
}
_ => {}
}
}
for entity in &change.del {
if let Some(Kind::Voice(voice)) = &entity.kind {
self.voices.remove(&voice.participant_id);
}
}
}
/// The next push `f` picks, skipping (and keeping track of) the others.
async fn until<T>(&mut self, what: &str, mut f: impl FnMut(&v1::Push) -> Option<T>) -> T {
within(what, async {
loop {
let push = self.pushes.recv().await.expect("the session lives");
self.absorb(&push);
if let Some(t) = f(&push) {
return t;
}
}
})
.await
}
/// Wait until the host shows our seat in LIVE: the first snapshot of the
/// TeamSpeak link may come after the session was handed out, so the syncs
/// can be empty and the voice states follow as changes. The seat then
/// names the channel we are in.
async fn settle(&mut self) {
let participant = self.seat.participant_id;
within("our voice state to appear", async {
while !self.voices.contains_key(&participant) {
let push = self.pushes.recv().await.expect("the session lives");
self.absorb(&push);
}
})
.await;
self.seat = self.voices[&participant].clone();
}
/// The next message `Change` of the CHAT scope of `channel` with `text`.
async fn message(&mut self, channel: u64, text: &str) -> v1::Message {
let chat = Some(scope(v1::ScopeKind::Chat, channel));
self.until(&format!("the message {text:?}"), |push| match &push.body {
Some(v1::push::Body::Change(change)) if change.scope == chat => {
change.put.iter().find_map(|e| match &e.kind {
Some(Kind::Message(message)) if message.text == text => Some(message.clone()),
_ => None,
})
}
_ => None,
})
.await
}
async fn close(self) {
self.session.close(v1::CloseCode::Normal, "");
within("the session to close", self.session.closed()).await;
}
}
// ---- the conformance suite ----------------------------------------------------
/// What a case is expected to do against a TeamSpeak session, and why.
enum Expect {
/// Every assertion of the case holds.
Passes,
/// The session lacks the feature the case needs (`Verdict::Skipped`).
Skipped(&'static str),
/// The case does not apply: it cannot run, or cannot pass, for this reason
/// (`cases_that_do_not_apply_fail` runs them and watches them fail).
NotRun(&'static str),
}
use Expect::{NotRun, Passes, Skipped};
/// Every case of the suite of the protocol repository at `c5bb6b9`, in its
/// order, with what a TeamSpeak session does with it. A case the suite gains
/// fails `the_suite_is_known` until it is listed here.
///
/// The suite is written for a backend that is a `FakeHost`. A case that needs
/// the backend gets the `FakeHandle` of an unrelated fake host, so the cases
/// that hold, kill or read it, or push into it, cannot run against a session of
/// a TeamSpeak server; the others write to places a TeamSpeak server does not
/// have (the suite's channels, a server with another id, `ScheduledEvent`,
/// `Emoji`, attachments). Each reason is what the case did when it was run.
const EXPECTED: [(&str, Expect); 17] = [
("welcome_matches_features", Passes),
(
"subscribe_syncs_the_scope",
NotRun("writes to channel 4001: rejected (NotFound) no such channel"),
),
(
"subscribe_resumes_from_a_cursor",
NotRun("writes to channel 4002: rejected (NotFound) no such channel"),
),
(
"put_answers_entities_and_pushes_the_change_with_the_same_rev",
NotRun("writes to channel 4003: rejected (NotFound) no such channel"),
),
(
"delete_answers_an_ack_and_pushes_the_removal",
NotRun(
"writes to channel 4004 first (no such channel); and TeamSpeak cannot delete a message, \
where the case needs only `chat`, not `chat.delete` (P8)",
),
),
(
"a_key_names_an_entity_without_its_server",
NotRun(
"rejected (NotFound) no such server; and it creates a ScheduledEvent and an Emoji, \
which TeamSpeak lacks, though it needs no feature (P8)",
),
),
("a_stale_rev_conflicts_and_a_patch_writes_only_its_paths", Skipped("chat.edit")),
("requests_apply_in_the_order_they_were_issued", Skipped("chat.edit")),
("list_pages_history", Skipped("chat.history")),
(
"cancel_before_apply_is_cancelled",
NotRun("holds the unrelated fake host, so the request is answered while it \"holds\""),
),
("idempotency_keys_apply_a_put_once", Skipped("idempotency")),
(
"notifications_are_fire_and_forget",
NotRun("reads the request log of the unrelated fake host: the notification never arrives"),
),
(
"renew_account_follows_the_feature",
NotRun("pushes a HostUpdate into the unrelated fake session's closed push channel"),
),
(
"media_loops_back",
NotRun(
"a TeamSpeak server does not return a client's own voice: the packet never loops back",
),
),
(
"files_round_trip",
NotRun(
"writes an AttachmentSlot: rejected (Unsupported) attachments are not offered; \
TeamSpeak has channel files, and the case needs `files`, not `chat.attachments` (P8)",
),
),
("close_ends_the_session", Passes),
(
"the_backend_can_end_the_session",
NotRun(
"kills the unrelated fake session, so closed() of this one never resolves; and a \
kick is Network(text), not Remote{KICKED}, until H1",
),
),
];
/// A fixture on a TeamSpeak session. The suite wants a `FakeHandle` on the
/// backend behind the session; a TeamSpeak server has none, so it gets the one
/// of an unrelated fake host, which the cases that are run never touch.
async fn fixture(dev: Dev) -> Fixture {
let (session, pushes, media) =
session(&dev, &VoiceOptions::new(dev.voice, dev.nick("conf"))).await;
let unrelated = FakeConnector::new();
let (params, _media) = voelin_proto::test_util::connect_params("fake://unrelated");
unrelated.connect(params).await.expect("a fake session");
let backend = unrelated.last_session().expect("a fake session");
Fixture::new(session, pushes, media, backend)
}
fn the_suite_is_known() {
let known: Vec<_> = EXPECTED.iter().map(|(name, _)| *name).collect();
let cases: Vec<_> = conformance::CASES.iter().map(|case| case.name).collect();
assert_eq!(known, cases, "the suite changed: list the new cases in EXPECTED");
}
/// The cases that apply run and pass, the ones that need a feature the session
/// lacks are skipped, and the rest are not run (their reason is in
/// [`EXPECTED`]).
async fn conformance_subset(dev: Dev) {
the_suite_is_known();
let harness = move || fixture(dev);
let (mut passed, mut skipped) = (0, 0);
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
match expect {
Passes => {
let verdict = conformance::run_case(&harness, case).await;
assert_eq!(verdict, Verdict::Passed, "{name} on {}", dev.name);
passed += 1;
}
Skipped(feature) => {
let verdict = conformance::run_case(&harness, case).await;
assert_eq!(verdict, Verdict::Skipped(feature), "{name} on {}", dev.name);
skipped += 1;
}
NotRun(reason) => eprintln!("{} {name}: not run: {reason}", dev.name),
}
}
assert_eq!((passed, skipped), (2, 4));
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_conformance_subset() {
if live() {
conformance_subset(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_conformance_subset() {
if live() {
conformance_subset(TS6).await;
}
}
// ---- what the suite cannot reach ----------------------------------------------
/// A message in the own channel is answered with the message as written, and
/// pushed to the CHAT scope of every session in the channel: to the other one
/// as a `Change`, and back to ours (the ids agree only with the native
/// session of H1: the answer has a local id, the echo the one of the
/// `Change`).
async fn chat_in_the_own_channel(dev: Dev) {
let mut a = Client::connect(&dev, &dev.nick("chat-a")).await;
let mut b = Client::connect(&dev, &dev.nick("chat-b")).await;
assert_eq!(a.seat.channel_id, b.seat.channel_id, "both sessions are in the default channel");
let channel = a.seat.channel_id;
a.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
b.subscribe(scope(v1::ScopeKind::Chat, channel)).await;
let text = format!("live-chat-{}", std::process::id());
let message = v1::Message { channel_id: channel, text: text.clone(), ..Default::default() };
let write = v1::Write {
entity: Some(v1::Entity { kind: Some(Kind::Message(message)) }),
paths: Vec::new(),
};
let put = Op::Put(v1::Put { writes: vec![write], ..Default::default() });
let Answer::Entities(answer) = a.ask(put).await.expect("the message is accepted") else {
panic!("a message is answered with entities")
};
let written = match &answer.items[..] {
[v1::Entity { kind: Some(Kind::Message(message)) }] => message.clone(),
other => panic!("one message expected, got {other:?}"),
};
assert_eq!((written.channel_id, written.text.as_str()), (channel, text.as_str()));
let heard = b.message(channel, &text).await;
assert_ne!(heard.id, 0);
assert_eq!(heard.channel_id, channel);
// And ours, back from the server: the same words, once.
let echo = a.message(channel, &text).await;
assert_ne!(echo.id, 0);
a.close().await;
b.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_chat_in_the_own_channel() {
if live() {
chat_in_the_own_channel(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_chat_in_the_own_channel() {
if live() {
chat_in_the_own_channel(TS6).await;
}
}
/// A move into a channel with a password or without room is refused with the
/// code the seam names: `PASSWORD` and `FULL`.
async fn refused_moves(dev: Dev) {
use voelin_query::{Command as Query, QueryClient};
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
let tag = std::process::id() % 10_000;
let create = |name: &str| {
Query::new("channelcreate")
.arg("channel_name", format!("{name}-{tag}"))
.arg("channel_flag_semi_permanent", 1)
};
let locked =
admin.send(&create("seam-locked").arg("channel_password", "secret")).await.unwrap()[0]
.parse::<u64>("cid")
.unwrap();
let full = create("seam-full")
.arg("channel_maxclients", 0)
.arg("channel_flag_maxclients_unlimited", 0);
let full = admin.send(&full).await.unwrap()[0].parse::<u64>("cid").unwrap();
// A key for the Normal group, which has to keep to passwords and limits.
let token = group_token(&admin, "Normal").await;
let check = {
let token = token.clone();
tokio::spawn(async move {
let mut options = VoiceOptions::new(dev.voice, dev.nick("moves"));
options.token = Some(token);
let client = Client::connect_with(&dev, options).await;
let code = |result: Result<v1::VoiceState, SessionError>| match result {
Err(SessionError::Rejected(error)) => error.code(),
other => panic!("expected a refusal, got {other:?}"),
};
assert_eq!(code(client.join(locked, "").await), v1::ErrorCode::Password);
assert_eq!(code(client.join(locked, "wrong").await), v1::ErrorCode::Password);
let seat = client.join(locked, "secret").await.expect("the right password");
assert_eq!(seat.channel_id, locked);
assert_eq!(code(client.join(full, "").await), v1::ErrorCode::Full);
client.close().await;
})
};
let result = check.await;
// Clean up before reporting a failure; the key is gone once used.
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
for cid in [locked, full] {
admin.send(&Query::new("channeldelete").arg("cid", cid).arg("force", 1)).await.unwrap();
}
if let Err(error) = result {
std::panic::resume_unwind(error.into_panic());
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_refused_moves() {
if live() {
refused_moves(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_refused_moves() {
if live() {
refused_moves(TS6).await;
}
}
/// A poke is a `Signal` to a participant: the other session gets it, with
/// the participant and the words of the sender.
async fn poke_between_sessions(dev: Dev) {
let a = Client::connect(&dev, &dev.nick("poke-a")).await;
let mut b = Client::connect(&dev, &dev.nick("poke-b")).await;
let text = format!("live-poke-{}", std::process::id());
let target = v1::SignalTarget {
server_id: a.server,
participant_id: b.seat.participant_id,
..Default::default()
};
let signal = v1::Signal {
to: Some(target),
body: Some(v1::signal::Body::Poke(v1::Poke { message: text.clone() })),
..Default::default()
};
a.ask(Op::Signal(signal)).await.expect("the poke is accepted");
let from = b
.until("the poke", |push| match &push.body {
Some(v1::push::Body::Signal(signal)) => match &signal.body {
Some(v1::signal::Body::Poke(poke)) if poke.message == text => {
Some(signal.from_participant)
}
_ => None,
},
_ => None,
})
.await;
assert_eq!(from, a.seat.participant_id);
a.close().await;
b.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_poke_between_sessions() {
if live() {
poke_between_sessions(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_poke_between_sessions() {
if live() {
poke_between_sessions(TS6).await;
}
}
/// One frame of Opus (20 ms, mono, fullband).
const OPUS: [u8; 3] = [0xf8, 0xff, 0xfe];
fn rtp(flow: FlowId, sequence: u16, marker: bool, payload: &[u8]) -> MediaPacket {
let mut header = RtpHeader::new(PT_OPUS, sequence, u32::from(sequence) * 960);
header.marker = marker;
let mut out = bytes::BytesMut::new();
header.write(flow, &mut out).expect("a header");
out.extend_from_slice(payload);
MediaPacket { flow, rtp: out.freeze() }
}
/// Voice sent on our slot arrives on the sender's slot at the other session's
/// media sink: the frames in order (the sequence is TeamSpeak's packet id, so
/// it only has to count up), the marker on the first, and an empty payload at
/// the end.
async fn voice_between_sessions(dev: Dev) {
let a = Client::connect(&dev, &dev.nick("voice-a")).await;
let mut b = Client::connect(&dev, &dev.nick("voice-b")).await;
assert_eq!(a.seat.channel_id, b.seat.channel_id);
let flow = FlowId::new(a.seat.slot, voice_sub::CHANNEL);
for n in 0..5u8 {
let frame = [0xf8, 0xff, 0xfe, n];
let packet = rtp(flow, u16::from(n), n == 0, &frame);
a.session.send_media(MediaClass::Voice, packet).expect("our own slot");
tokio::time::sleep(Duration::from_millis(20)).await;
}
a.session.send_media(MediaClass::Voice, rtp(flow, 5, false, &[])).expect("the end");
let mut heard = Vec::new();
while let Some(packet) = b.media.recv_within(Duration::from_secs(5)).await {
let view = RtpView::parse(&packet.rtp).expect("RTP");
heard.push((packet.flow, view.sequence(), view.marker(), view.payload().to_vec()));
if view.payload().is_empty() {
break;
}
}
assert!(heard.len() >= 2, "{heard:?}");
assert!(heard.iter().all(|(heard_flow, ..)| *heard_flow == flow), "{heard:?}");
let (_, _, first_marker, first_payload) = &heard[0];
assert!(*first_marker, "the first packet of the spurt carries the marker: {heard:?}");
assert_eq!(&first_payload[..3], &OPUS[..], "{heard:?}");
let (end_flow, _, end_marker, end_payload) = heard.last().expect("an end");
assert!(
end_payload.is_empty() && !*end_marker,
"the spurt ends with an empty payload: {heard:?}"
);
assert_eq!(*end_flow, flow);
let sequences: Vec<_> = heard.iter().map(|(_, sequence, ..)| *sequence).collect();
assert!(
sequences.windows(2).all(|pair| pair[1] == pair[0].wrapping_add(1)),
"the sequence counts up by one: {sequences:?}"
);
// Voice on a slot that is not ours is refused before it reaches the server.
let other = FlowId::new(a.seat.slot + 1000, voice_sub::CHANNEL);
assert!(a.session.send_media(MediaClass::Voice, rtp(other, 0, true, &OPUS)).is_err());
a.close().await;
b.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_voice_between_sessions() {
if live() {
voice_between_sessions(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_voice_between_sessions() {
if live() {
voice_between_sessions(TS6).await;
}
}
/// A channel file written with `write_file` and read back from an offset with
/// `read_file`: the head names the file and its size, the body starts where
/// the offset says.
async fn channel_file_from_an_offset(dev: Dev) {
use voelin_query::{Command as Query, QueryClient};
// Guests may not upload: a key for the Server Admin group.
let (admin, _) = QueryClient::connect(&dev.query()).await.expect("the query login");
let token = group_token(&admin, "Server Admin").await;
let check = tokio::spawn({
let token = token.clone();
async move { channel_file_with_a_key(dev, token).await }
});
let result = check.await;
let _ = admin.send(&Query::new("privilegekeydelete").arg("token", &token)).await;
if let Err(error) = result {
std::panic::resume_unwind(error.into_panic());
}
}
/// A one-time key for the server group `name` (a template group, type 1).
async fn group_token(admin: &voelin_query::QueryClient, name: &str) -> String {
use voelin_query::Command as Query;
let groups = admin.send(&Query::new("servergrouplist")).await.unwrap();
let group = groups
.iter()
.find(|g| g.get("name") == Some(name) && g.get("type") == Some("1"))
.and_then(|g| g.parse::<u64>("sgid"))
.unwrap_or_else(|| panic!("a {name} server group"));
let key =
Query::new("privilegekeyadd").arg("tokentype", 0).arg("tokenid1", group).arg("tokenid2", 0);
admin.send(&key).await.unwrap()[0].get("token").unwrap().to_owned()
}
async fn channel_file_with_a_key(dev: Dev, token: String) {
let mut options = VoiceOptions::new(dev.voice, dev.nick("files"));
options.token = Some(token);
let a = Client::connect_with(&dev, options).await;
let channel = a.seat.channel_id;
let name = format!("seam-{}.bin", std::process::id());
let path = format!("/{name}");
let data: Vec<u8> = (0..3_000usize).map(|i| (i * 7 % 251) as u8).collect();
let target = v1::FilePath { channel_id: channel, path: path.clone(), password: String::new() };
let write = v1::FileWrite {
target: Some(v1::file_write::Target::Path(target.clone())),
size: data.len() as u64,
offset: 0,
overwrite: true,
sha256: Default::default(),
};
let mut upload =
within("the upload to open", a.session.write_file(write)).await.expect("an upload");
upload.body.write_all(&data).await.expect("the body");
upload.body.shutdown().await.expect("the end of the body");
let stored = within("the server to keep it", upload.done).await.expect("the file is stored");
assert!(
stored.items.iter().any(|e| matches!(&e.kind, Some(Kind::File(f)) if f.name == name)),
"{stored:?}"
);
let read = v1::FileRead {
target: Some(v1::file_read::Target::Path(target.clone())),
offset: 1_000,
length: 0,
};
let mut download =
within("the download to open", a.session.read_file(read)).await.expect("a download");
let size = download.head.items.iter().find_map(|e| match &e.kind {
Some(Kind::File(file)) => Some(file.size),
_ => None,
});
assert_eq!(size, Some(3_000), "{:?}", download.head);
let mut body = Vec::new();
within("the body", download.body.read_to_end(&mut body)).await.expect("the body");
assert_eq!(body, data[1_000..], "the body starts at the offset");
// Clean up what we put on the server.
let key = v1::FileEntry { channel_id: channel, path: "/".into(), name, ..Default::default() };
let delete = Op::Delete(v1::Delete {
keys: vec![v1::Entity { kind: Some(Kind::File(key)) }],
..Default::default()
});
let _ = a.ask(delete).await;
a.close().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn ts3_channel_file_from_an_offset() {
if live() {
channel_file_from_an_offset(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn ts6_channel_file_from_an_offset() {
if live() {
channel_file_from_an_offset(TS6).await;
}
}
// ---- the cases that do not apply ----------------------------------------------
/// The cases of [`EXPECTED`] that do not apply fail against a session of a
/// TeamSpeak server, each with a panic of its own (its first line is printed):
/// the reasons of the table are what they did when they were run. A case that
/// passes one day (with the native session of H1) is to be moved to `Passes`.
///
/// Ignored by default: the cases that wait for a backend that is not there
/// take their three seconds each.
async fn cases_that_do_not_apply_fail(dev: Dev) {
// A case the suite gained is not in `EXPECTED`, and the zip below would leave
// it out without a word.
the_suite_is_known();
for (case, (name, expect)) in conformance::CASES.iter().zip(&EXPECTED) {
let NotRun(reason) = expect else { continue };
let harness = move || async move {
let mut fixture = fixture(dev).await;
fixture.step = Duration::from_secs(3);
fixture
};
match tokio::spawn(async move { conformance::run_case(&harness, case).await }).await {
Err(error) if error.is_panic() => {
let payload = error.into_panic();
let message = payload
.downcast_ref::<String>()
.cloned()
.or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned()))
.unwrap_or_default();
let first = message.lines().next().unwrap_or_default();
eprintln!("{} {name}: failed as expected ({reason}): {first}", dev.name);
}
other => panic!("{name} on {} was expected to fail, and: {other:?}", dev.name),
}
}
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
async fn ts3_cases_that_do_not_apply_fail() {
if live() {
cases_that_do_not_apply_fail(TS3).await;
}
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "runs the conformance cases that cannot pass and waits for their timeouts"]
async fn ts6_cases_that_do_not_apply_fail() {
if live() {
cases_that_do_not_apply_fail(TS6).await;
}
}
@@ -0,0 +1,245 @@
//! Voice across the seam, TeamSpeak side (`docs/session-seam.md` section
//! 6.2): TeamSpeak's Opus packets as RTP on the talker's slot, and RTP on our
//! own slot as TeamSpeak's `EncodedVoice`. Nothing is transcoded
//! (protocol section 1.2): the Opus payload is the same bytes both ways.
use std::collections::HashMap;
use std::time::{Duration, Instant};
use bytes::BytesMut;
use voelin_audio::{EncodedVoice, VoiceCodec, VoicePacket};
use voelin_proto::link::{FlowId, MediaPacket, voice_sub};
use voelin_proto::media::opus::{self, Toc};
use voelin_proto::media::payload::{OPUS_20_MS_TICKS, OPUS_CLOCK_RATE, PT_OPUS};
use voelin_proto::media::{RtpHeader, RtpView};
use super::entities::slot;
/// Silence this long between two packets of a talker starts a new talk spurt
/// (the marker bit is set on the first packet of it).
const SPURT_GAP: Duration = Duration::from_millis(250);
/// What is kept of the last packet of a talker.
struct Talker {
timestamp: u32,
sequence: u16,
at: Instant,
/// The 48 kHz ticks the last packet spans.
ticks: u32,
/// The last packet ended the spurt.
ended: bool,
}
/// Wraps what a TeamSpeak connection receives into RTP.
#[derive(Default)]
pub(super) struct Downlink {
talkers: HashMap<u16, Talker>,
}
impl Downlink {
/// `packet` as the RTP packet of its talker's slot. The sequence number is
/// TeamSpeak's packet id (both 16 bits); the timestamp advances by each
/// packet's duration (its Opus table-of-contents byte) on the packet id's
/// counter, so it never goes back when the id wraps, and by wall-clock time
/// across silences, so a silence is not compressed. The marker is set on
/// the first packet after an end or a gap, and an end is an empty payload.
pub(super) fn wrap(&mut self, packet: &VoicePacket, now: Instant) -> Option<MediaPacket> {
let id = packet.talker.0;
let sub = if packet.whisper { voice_sub::FIRST_TALK_TARGET } else { voice_sub::CHANNEL };
let flow = FlowId::new(slot(id), sub);
let end = packet.is_end();
let (timestamp, marker) = match self.talkers.get(&id) {
None => (0, !end),
Some(last) => {
let gap = now.saturating_duration_since(last.at);
if last.ended || gap > SPURT_GAP {
// A new spurt: the time that passed since the last packet.
let wall = (gap.as_micros() * u128::from(OPUS_CLOCK_RATE) / 1_000_000) as u32;
(last.timestamp.wrapping_add(last.ticks.max(wall)), !end)
} else {
let ahead = packet.seq.wrapping_sub(last.sequence);
if ahead == 0 || ahead >= 0x8000 {
// A duplicate or a late packet: where it belongs, and the
// state keeps what the latest packet said.
let back = u32::from(last.sequence.wrapping_sub(packet.seq));
let at = last.timestamp.wrapping_sub(back * last.ticks);
return self.finish(flow, packet, at, false);
}
(last.timestamp.wrapping_add(u32::from(ahead) * last.ticks), false)
}
}
};
let ticks =
if end { 0 } else { opus::packet_ticks(&packet.payload).unwrap_or(OPUS_20_MS_TICKS) };
self.talkers
.insert(id, Talker { timestamp, sequence: packet.seq, at: now, ticks, ended: end });
self.finish(flow, packet, timestamp, marker)
}
fn finish(
&self,
flow: FlowId,
packet: &VoicePacket,
timestamp: u32,
marker: bool,
) -> Option<MediaPacket> {
let mut header = RtpHeader::new(PT_OPUS, packet.seq, timestamp);
header.marker = marker;
// An end is an empty payload, also where the server sent one byte.
let payload = if packet.is_end() { &[][..] } else { &packet.payload[..] };
let mut out = BytesMut::with_capacity(header.encoded_len() + payload.len());
header.write(flow, &mut out).ok()?;
out.extend_from_slice(payload);
Some(MediaPacket { flow, rtp: out.freeze() })
}
/// Forget a talker (it left the server).
pub(super) fn forget(&mut self, client: u16) {
self.talkers.remove(&client);
}
}
/// The voice a media packet of our own slot carries, for TeamSpeak: its
/// payload, and `Music` when the Opus packet is stereo. `None` for a packet
/// that is no RTP.
pub(super) fn uplink(packet: &MediaPacket) -> Option<EncodedVoice> {
let view = RtpView::parse(&packet.rtp).ok()?;
let payload = view.payload();
let codec = match Toc::parse(payload) {
Ok(toc) if toc.stereo() => VoiceCodec::Music,
_ => VoiceCodec::Voice,
};
Some(EncodedVoice { codec, payload: payload.to_vec() })
}
/// An RTP packet of voice, for tests of both sides.
#[cfg(test)]
pub(super) fn rtp_packet(
flow: FlowId,
sequence: u16,
timestamp: u32,
marker: bool,
payload: &[u8],
) -> bytes::Bytes {
let mut header = RtpHeader::new(PT_OPUS, sequence, timestamp);
header.marker = marker;
let mut out = BytesMut::new();
header.write(flow, &mut out).unwrap();
out.extend_from_slice(payload);
out.freeze()
}
#[cfg(test)]
mod tests {
use bytes::Bytes;
use voelin_audio::TalkerId;
use super::*;
fn voice(talker: u16, seq: u16, payload: &[u8], whisper: bool) -> VoicePacket {
VoicePacket {
talker: TalkerId(talker),
seq,
codec: VoiceCodec::Voice,
whisper,
payload: payload.to_vec(),
}
}
/// An Opus packet of 20 ms in a CELT-only frame (config 16 is 2.5 ms; 19
/// is 20 ms), mono, one frame.
const OPUS_20_MS: [u8; 3] = [0x98, 0x01, 0x02];
fn view(packet: &MediaPacket) -> RtpView<'_> {
RtpView::parse(&packet.rtp).unwrap()
}
#[test]
fn a_spurt_is_sequenced_by_the_packet_id_with_a_marker_on_its_first_packet() {
let mut down = Downlink::default();
let t0 = Instant::now();
let first = down.wrap(&voice(7, 65_534, &OPUS_20_MS, false), t0).unwrap();
let v = view(&first);
assert!(v.marker());
assert_eq!((v.ssrc(), first.flow), (FlowId::new(8, 0).0, FlowId::new(8, 0)));
assert_eq!((v.sequence(), v.timestamp()), (65_534, 0));
// The id wraps; the timestamp keeps counting.
let t1 = t0 + Duration::from_millis(20);
let second = down.wrap(&voice(7, 65_535, &OPUS_20_MS, false), t1).unwrap();
let third =
down.wrap(&voice(7, 0, &OPUS_20_MS, false), t1 + Duration::from_millis(20)).unwrap();
assert!(!view(&second).marker() && !view(&third).marker());
assert_eq!(view(&second).timestamp(), OPUS_20_MS_TICKS);
assert_eq!((view(&third).sequence(), view(&third).timestamp()), (0, 2 * OPUS_20_MS_TICKS));
}
#[test]
fn the_end_is_an_empty_payload_and_the_next_packet_has_a_marker() {
let mut down = Downlink::default();
let t0 = Instant::now();
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
let end = down.wrap(&voice(7, 2, &[], false), t0 + Duration::from_millis(20)).unwrap();
assert!(view(&end).payload().is_empty() && !view(&end).marker());
// TeamSpeak's single byte after a talk is an end too.
let mut down = Downlink::default();
down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
let end = down.wrap(&voice(7, 2, &[0], false), t0 + Duration::from_millis(20)).unwrap();
assert!(view(&end).payload().is_empty());
let next =
down.wrap(&voice(7, 3, &OPUS_20_MS, false), t0 + Duration::from_millis(60)).unwrap();
assert!(view(&next).marker());
}
#[test]
fn a_silence_is_not_compressed() {
let mut down = Downlink::default();
let t0 = Instant::now();
let first = down.wrap(&voice(7, 1, &OPUS_20_MS, false), t0).unwrap();
let again =
down.wrap(&voice(7, 2, &OPUS_20_MS, false), t0 + Duration::from_secs(2)).unwrap();
assert!(view(&again).marker(), "a gap starts a spurt");
// Two seconds of wall-clock time are 96,000 ticks of the 48 kHz clock.
assert_eq!(view(&again).timestamp() - view(&first).timestamp(), 96_000);
}
#[test]
fn whispers_ride_sub_flow_1_and_talkers_have_slots_of_their_own() {
let mut down = Downlink::default();
let now = Instant::now();
let whisper = down.wrap(&voice(300, 1, &OPUS_20_MS, true), now).unwrap();
assert_eq!((whisper.flow.slot(), whisper.flow.sub()), (301, 1));
let channel = down.wrap(&voice(300, 2, &OPUS_20_MS, false), now).unwrap();
assert_eq!((channel.flow.slot(), channel.flow.sub()), (301, 0));
}
#[test]
fn a_packet_that_is_not_in_order_keeps_the_state_of_the_latest() {
let mut down = Downlink::default();
let t0 = Instant::now();
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0).unwrap();
down.wrap(&voice(7, 11, &OPUS_20_MS, false), t0 + Duration::from_millis(20)).unwrap();
let late =
down.wrap(&voice(7, 10, &OPUS_20_MS, false), t0 + Duration::from_millis(25)).unwrap();
assert_eq!(view(&late).timestamp(), 0, "where packet 10 belongs");
let next =
down.wrap(&voice(7, 12, &OPUS_20_MS, false), t0 + Duration::from_millis(40)).unwrap();
assert_eq!(view(&next).timestamp(), 2 * OPUS_20_MS_TICKS);
}
#[test]
fn our_voice_loses_its_header_and_stereo_is_music() {
let flow = FlowId::new(8, 0);
let mono = MediaPacket { flow, rtp: rtp_packet(flow, 0, 0, true, &OPUS_20_MS) };
let voice = uplink(&mono).unwrap();
assert_eq!((voice.codec, voice.payload.as_slice()), (VoiceCodec::Voice, &OPUS_20_MS[..]));
// The same TOC with the stereo bit.
let stereo_toc = [OPUS_20_MS[0] | 0x04, 1, 2];
let stereo = MediaPacket { flow, rtp: rtp_packet(flow, 1, 960, false, &stereo_toc) };
assert_eq!(uplink(&stereo).unwrap().codec, VoiceCodec::Music);
// The end of a spurt: an empty payload.
let end = MediaPacket { flow, rtp: rtp_packet(flow, 2, 1920, false, &[]) };
assert!(uplink(&end).unwrap().is_end());
// Not RTP.
assert!(uplink(&MediaPacket { flow, rtp: Bytes::from_static(&[1, 2, 3]) }).is_none());
}
}
+887
View File
@@ -0,0 +1,887 @@
//! A TeamSpeak connection as a `voelin_proto::link::Session`
//! (`docs/session-seam.md`, "the TeamSpeak side").
//!
//! [`LinkSession`] is a `Session` over any [`ServerLink`]:
//! it turns the link's `LinkCmd`s and `LinkEvent`s (the client's older,
//! TeamSpeak-shaped vocabulary) into v1 entities, pushes and answers. With
//! `TsLink` inside it is the in-process TeamSpeak `Session`; with a fake link
//! inside it is what the link tests of the engine run through. [`TsConnector`]
//! is the `Connector` that makes them for `ts3server://` and `teamspeak://`
//! addresses.
//!
//! This module and the files it is made of are TeamSpeak's: they keep the
//! TeamSpeak types (`tsclientlib`'s identity and client version) in
//! [`inner_options`], the reverse of what the engine's `connect_params` wrote,
//! and everything else is v1 and the client's own model. In the second half
//! of the decoupling plan they move, with `TsLink`, to the TeamSpeak gateway
//! (`voelin-gateway-ts` of VoelinGateWay).
mod driver;
pub(crate) mod entities;
pub(crate) mod ids;
#[cfg(test)]
mod live_tests;
mod media;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::task::{Context, Poll};
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use bytes::Bytes;
use tokio::io::{AsyncReadExt, AsyncWrite};
use tokio::sync::{broadcast, mpsc, oneshot, watch};
use voelin_model::{Link, ServerDetails};
use voelin_proto::link::{
BoxFuture, CloseReason, ConnectParams, Connected, Connector, Credential, Download, Features,
LinkStats, MAX_RTP, MediaClass, MediaError, MediaPacket, Placement, Sent, Session,
SessionError, Upload, placement, voice_sub,
};
use voelin_proto::v1::{self, response::Result as Answer};
use self::driver::{Cmd, Config, Driver, Parts, rejected};
use super::{ConnectOptions, ServerLink, TsLink, identity, versions};
use crate::BackendInfo;
use crate::link::{
BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort,
VERSION_PARAM,
};
/// The `Credential::Foreign` kind of a stored TeamSpeak identity.
const IDENTITY_KIND: &str = voelin_identity::KIND_TEAMSPEAK;
/// How long the link may take to report its first snapshot after it said it
/// is connected; the snapshot gives the `Welcome` its own user.
const FIRST_SNAPSHOT: Duration = Duration::from_millis(250);
static SESSIONS: AtomicU64 = AtomicU64::new(1);
fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or_default()
}
// ---- what the engine hands a connector ------------------------------------
/// The options a TeamSpeak link is connected with: the reverse of
/// `link::connect_params`. A client version spec that [`versions::resolve`]
/// refuses fails the connect, in words.
fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOptions, SessionError> {
let link = match Link::parse(&params.address) {
Some(Link::Server(link)) => link,
_ => {
// Without the query: a channel password rides in it.
let shown = crate::link::without_query(&params.address);
return Err(SessionError::Protocol(format!("not a TeamSpeak server address: {shown}")));
}
};
let identity = match &params.credential {
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
// The refusal never quotes the JSON: it holds the private key, and the
// JSON reader's own message would show a key that does not import.
let json = std::str::from_utf8(blob).map_err(|_| {
SessionError::Protocol(
"the TeamSpeak identity cannot be read: it is not text".into(),
)
})?;
Some(identity::from_json(json).map_err(|e| SessionError::Protocol(e.to_string()))?)
}
_ => {
return Err(SessionError::Protocol(
"a TeamSpeak server needs a TeamSpeak identity".into(),
));
}
};
let spec = params
.address
.split_once('?')
.and_then(|(_, query)| {
query.split('&').find_map(|pair| pair.strip_prefix(&format!("{VERSION_PARAM}=")))
})
.map(|text| {
URL_SAFE_NO_PAD
.decode(text)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.ok_or_else(|| SessionError::Protocol("the client version cannot be read".into()))
})
.transpose()?;
let client_version = match spec {
None => None,
Some(spec) => versions::resolve(&spec).map_err(|e| {
SessionError::Protocol(format!("invalid client compatibility version: {e}"))
})?,
};
let nonempty = |text: &str| (!text.is_empty()).then(|| text.to_owned());
Ok(ConnectOptions {
address: link.address(),
nickname: nonempty(&params.hello.nickname).or(link.nickname.clone()).unwrap_or_default(),
identity,
client_version,
server_password: nonempty(&params.hello.password).or(link.password.clone()),
channel: link.channel.clone(),
channel_password: link.channel_password.clone(),
token: nonempty(&params.hello.invite_code).or(link.token.clone()),
audio: ctx.audio,
stream_peer: ctx.stream_peer.clone(),
})
}
// ---- backend and features ---------------------------------------------------
/// The server software as v1 names it (table 4.7): `teamspeak` with the
/// flavor `ts3` or `ts6`; what is not a TeamSpeak product as it is.
pub(crate) fn backend_to_v1(backend: &BackendInfo) -> v1::BackendInfo {
let (product, flavor) = match backend.product.as_str() {
"TeamSpeak 3" => ("teamspeak", "ts3"),
"TeamSpeak 6" => ("teamspeak", "ts6"),
// A TeamSpeak server the engine does not recognise: the version it
// sent, no flavor.
"" => ("teamspeak", ""),
other => (other, ""),
};
v1::BackendInfo {
product: product.into(),
version: backend.version.clone(),
flavor: flavor.into(),
}
}
/// The features a TeamSpeak connection offers, from what its link can do
/// (`docs/session-seam.md` section 4.7).
pub(crate) fn features_of(capabilities: &voelin_model::Capabilities) -> Vec<&'static str> {
let mut features =
vec!["voice", "chat", "chat.bbcode", "dm", "sync.delta", "roles", "roles.channel"];
if capabilities.file_transfer {
features.extend(["files", "files.upload"]);
}
if capabilities.offline_messages {
features.push("mailbox");
}
if capabilities.streams {
features.extend(["streams", "streams.p2p", "streams.audio", "streams.approval"]);
}
features
}
// ---- the session ------------------------------------------------------------
/// A `Session` over a [`ServerLink`]: the TeamSpeak side of the seam.
pub(crate) struct LinkSession {
welcome: v1::Welcome,
features: Features,
cmds: mpsc::UnboundedSender<Cmd>,
closed: watch::Receiver<Option<CloseReason>>,
/// The media slot of our client; the driver changes it when we are another
/// client after TeamSpeak's own reconnect.
own_slot: Arc<AtomicU32>,
}
fn closed_reason(closed: &watch::Receiver<Option<CloseReason>>) -> CloseReason {
closed.borrow().clone().unwrap_or_else(|| CloseReason::Network("the connection ended".into()))
}
impl Session for LinkSession {
fn welcome(&self) -> &v1::Welcome {
&self.welcome
}
fn features(&self) -> Features {
self.features.clone()
}
fn request(&self, op: v1::request::Op) -> BoxFuture<Result<Answer, SessionError>> {
let closed = self.closed.clone();
match placement(&op) {
Placement::Invalid => {
return Box::pin(async {
Err(SessionError::Protocol("a Hello is part of connecting".into()))
});
}
Placement::OwnStream
if matches!(op, v1::request::Op::FileRead(_) | v1::request::Op::FileWrite(_)) =>
{
return Box::pin(async {
Err(SessionError::Protocol("files go through read_file and write_file".into()))
});
}
_ => {}
}
// Queued now, in the order of the calls, not when the future is polled.
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Request { op, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn notify(&self, op: v1::request::Op) -> Result<(), SessionError> {
// Only an op of the control stream can go without an answer: a Hello is
// part of connecting, and a List and the file transfers have streams
// (and answers) of their own.
match placement(&op) {
Placement::Control => {}
Placement::Invalid => {
return Err(SessionError::Protocol("a Hello is part of connecting".into()));
}
Placement::OwnStream => {
return Err(SessionError::Protocol(
"a List and the file transfers have a stream and an answer of their own, \
they cannot be sent without one"
.into(),
));
}
}
// The task may be on its way out and not have dropped its queue yet.
if self.closed.borrow().is_some() {
return Err(SessionError::Closed(closed_reason(&self.closed)));
}
self.cmds
.send(Cmd::Notify(op))
.map_err(|_| SessionError::Closed(closed_reason(&self.closed)))
}
fn read_file(&self, request: v1::FileRead) -> BoxFuture<Result<Download, SessionError>> {
let closed = self.closed.clone();
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Read { request, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn write_file(&self, request: v1::FileWrite) -> BoxFuture<Result<Upload, SessionError>> {
let closed = self.closed.clone();
let (reply, answer) = oneshot::channel();
if self.cmds.send(Cmd::Write { request, reply }).is_err() {
return Box::pin(async move { Err(SessionError::Closed(closed_reason(&closed))) });
}
Box::pin(async move {
match answer.await {
Ok(answer) => answer,
Err(_) => Err(SessionError::Closed(closed_reason(&closed))),
}
})
}
fn send_media(&self, class: MediaClass, packet: MediaPacket) -> Result<Sent, MediaError> {
let flow = packet.flow;
if self.closed.borrow().is_some() {
return Err(MediaError::Closed);
}
if packet.rtp.len() > MAX_RTP {
return Err(MediaError::TooLarge { len: packet.rtp.len(), max: MAX_RTP });
}
// Only our voice to the channel: TeamSpeak whispers and priority voice,
// like video, are not offered here.
if class != MediaClass::Voice
|| flow.slot() != self.own_slot.load(Ordering::Relaxed)
|| flow.sub() != voice_sub::CHANNEL
{
return Err(MediaError::NotOwned(flow));
}
let voice = media::uplink(&packet).ok_or(MediaError::NotOwned(flow))?;
self.cmds.send(Cmd::Audio(voice)).map_err(|_| MediaError::Closed)?;
Ok(Sent::Queued)
}
fn stats(&self) -> LinkStats {
LinkStats { max_rtp: MAX_RTP, ..Default::default() }
}
fn close(&self, code: v1::CloseCode, reason: &str) {
let _ = self.cmds.send(Cmd::Close { code, reason: reason.to_owned() });
}
fn closed(&self) -> BoxFuture<CloseReason> {
let mut closed = self.closed.clone();
Box::pin(async move {
let reason = closed.wait_for(Option::is_some).await.ok().and_then(|r| r.clone());
reason.unwrap_or_else(|| closed_reason(&closed))
})
}
}
/// The write half of an upload: ending it tells the other half of the
/// upload that the file is all there.
struct UploadBody {
inner: tokio::io::WriteHalf<BoxDuplex>,
ended: Option<oneshot::Sender<()>>,
}
impl AsyncWrite for UploadBody {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let done = Pin::new(&mut self.inner).poll_shutdown(cx);
if matches!(done, Poll::Ready(Ok(())))
&& let Some(ended) = self.ended.take()
{
let _ = ended.send(());
}
done
}
}
/// An upload over the transfer connection `stream`: the body writes to it,
/// and `done` resolves once the body is shut down and the server has closed
/// the connection (or 30 s passed), with the file as `stored`.
fn upload(stream: BoxDuplex, stored: v1::FileEntry) -> Upload {
let (mut read, write) = tokio::io::split(stream);
let (ended, shut) = oneshot::channel();
let done: BoxFuture<Result<v1::Entities, SessionError>> = Box::pin(async move {
if shut.await.is_err() {
return Err(rejected(v1::ErrorCode::Cancelled, "the upload was dropped"));
}
// The server closes the connection once it has everything.
let _ = tokio::time::timeout(Duration::from_secs(30), read.read(&mut [0u8; 1])).await;
Ok(v1::Entities {
items: vec![v1::Entity { kind: Some(v1::entity::Kind::File(stored)) }],
..Default::default()
})
});
Upload { body: Box::pin(UploadBody { inner: write, ended: Some(ended) }), done }
}
// ---- the connector ----------------------------------------------------------
/// The `Connector` of a [`ServerLink`]: its sessions are [`LinkSession`]s.
#[derive(Clone)]
pub(crate) struct LinkConnector {
link: Arc<dyn ServerLink>,
schemes: &'static [&'static str],
/// Serves every scheme (the engine's tests give a link of their own).
any: bool,
}
impl LinkConnector {
/// A connector for `schemes`.
pub(crate) fn new(link: Arc<dyn ServerLink>, schemes: &'static [&'static str]) -> Self {
Self { link, schemes, any: false }
}
/// A connector for addresses of every scheme.
#[cfg(test)]
pub(crate) fn any(link: Arc<dyn ServerLink>) -> Self {
Self { link, schemes: &[], any: true }
}
}
impl Connector for LinkConnector {
fn schemes(&self) -> &'static [&'static str] {
self.schemes
}
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
let connect = connect_link(self.link.clone(), params, LocalCtx::standalone());
Box::pin(async move { Ok(connect.await?.connected) })
}
}
impl LocalConnector for LinkConnector {
fn accepts(&self, scheme: &str) -> bool {
self.any || self.schemes.contains(&scheme)
}
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
Box::pin(connect_link(self.link.clone(), params, ctx))
}
}
/// Connects to TeamSpeak 3 and 6 servers (`ts3server://` and `teamspeak://`)
/// with `tsclientlib`: a `LinkSession` over a `TsLink` for every connection.
///
/// Clones share one account: the main myTeamSpeak account that every
/// connection of the connector presents ([`TsConnector::set_myts_identity`],
/// [`TsConnector::set_myts_data`]), also those made before it was set.
/// Register a connector in the engine's registry with
/// [`Backends::register_teamspeak`](crate::Backends::register_teamspeak) and
/// keep a clone to set the account.
#[derive(Clone)]
pub struct TsConnector {
connector: LinkConnector,
link: Arc<TsLink>,
}
impl Default for TsConnector {
fn default() -> Self {
Self::new()
}
}
impl TsConnector {
/// A connector that presents no account until it is given one.
pub fn new() -> Self {
let link = Arc::new(TsLink::new());
Self { connector: LinkConnector::new(link.clone(), &["ts3server", "teamspeak"]), link }
}
/// The main account's proof for every current and future connection of
/// this connector (and its clones): a myTS ID signed with the account's
/// key. Connections that are up show the server the new proof, and those
/// that connect later present it from the start; `None` is a sign-out.
pub fn set_myts_identity(&self, identity: Option<Arc<tsproto::myts::Identity>>) {
self.link.account().set_identity(identity);
}
/// What servers are shown of the main account: its avatar and badges with
/// their certificates, its User Tag (TeamSpeak 6). It is sent to every
/// connection that presents the account's myTS ID, once connected and when
/// it changes; cleared on a sign-out (`None`).
pub fn set_myts_data(&self, data: Option<Arc<tsclientlib::MytsData>>) {
self.link.account().set_data(data);
}
}
impl Connector for TsConnector {
fn schemes(&self) -> &'static [&'static str] {
self.connector.schemes()
}
fn connect(&self, params: ConnectParams) -> BoxFuture<Result<Connected, SessionError>> {
self.connector.connect(params)
}
}
impl LocalConnector for TsConnector {
fn connect_local(
&self,
params: ConnectParams,
ctx: LocalCtx,
) -> BoxFuture<Result<LocalConnected, SessionError>> {
self.connector.connect_local(params, ctx)
}
}
/// What the link told when it connected.
struct Joined {
name: String,
backend: BackendInfo,
capabilities: voelin_model::Capabilities,
own_client: u16,
server_uid: String,
own_uid: Option<String>,
}
fn ended_error(reason: Option<String>) -> SessionError {
SessionError::Closed(match reason {
Some(reason) => CloseReason::Network(reason),
None => CloseReason::Remote { code: v1::CloseCode::Normal as u64, reason: String::new() },
})
}
/// Wait for the link to say it is connected (or that it failed).
async fn wait_connected(
events: &mut mpsc::UnboundedReceiver<LinkEvent>,
) -> Result<Joined, SessionError> {
loop {
match events.recv().await {
Some(LinkEvent::Connected {
name,
backend,
capabilities,
own_client,
server_uid,
own_uid,
}) => {
return Ok(Joined { name, backend, capabilities, own_client, server_uid, own_uid });
}
Some(LinkEvent::Disconnected(reason)) => return Err(ended_error(reason)),
Some(_) => {}
None => return Err(ended_error(Some("the connection ended".into()))),
}
}
}
/// Open a [`LinkSession`] over `link` to the address in `params`.
async fn connect_link(
link: Arc<dyn ServerLink>,
params: ConnectParams,
ctx: LocalCtx,
) -> Result<LocalConnected, SessionError> {
let options = inner_options(&params, &ctx)?;
let nickname = options.nickname.clone();
let (inner_tx, inner_rx) = mpsc::unbounded_channel();
let (events_tx, mut events) = mpsc::unbounded_channel();
// The link answers requests on a bus of its own: this session reads the
// answers, and passes on the rest to the engine's.
let (bus_tx, bus) = broadcast::channel(4096);
let inner_ctx = LinkCtx { events: bus_tx, ..ctx.link.clone() };
link.spawn(options, inner_ctx, inner_rx, events_tx);
let joined = match tokio::time::timeout(params.timeout, wait_connected(&mut events)).await {
Ok(joined) => joined?,
Err(_) => {
let _ = inner_tx.send(LinkCmd::Disconnect);
return Err(SessionError::Timeout);
}
};
// The link reports its first snapshot right after it says it is connected;
// the session needs it to know the own user.
let mut early: Vec<LinkEvent> = Vec::new();
let _ = tokio::time::timeout(FIRST_SNAPSHOT, async {
while let Some(event) = events.recv().await {
let stop = matches!(event, LinkEvent::Presence(_) | LinkEvent::Disconnected(_));
early.push(event);
if stop {
break;
}
}
})
.await;
if let Some(LinkEvent::Disconnected(reason)) = early.last() {
return Err(ended_error(reason.clone()));
}
let own_database_id = early.iter().find_map(|event| match event {
LinkEvent::Presence(presence) => {
presence.clients.get(&joined.own_client).and_then(|c| c.database_id)
}
_ => None,
});
let ts6 = joined.backend.product == "TeamSpeak 6";
let own_user =
own_database_id.or_else(|| joined.own_uid.as_deref().map(ids::synthetic_user)).unwrap_or(0);
let features = features_of(&joined.capabilities);
let welcome = v1::Welcome {
user_id: own_user,
session_id: SESSIONS.fetch_add(1, Ordering::Relaxed),
uid: joined.own_uid.as_deref().and_then(ids::uid_bytes).unwrap_or_default().into(),
host: Some(v1::HostInfo {
host_key: Bytes::new(),
name: joined.name.clone(),
product: joined.backend.product.clone(),
version: joined.backend.version.clone(),
backend: Some(backend_to_v1(&joined.backend)),
icon: None,
}),
features: features.iter().map(|f| (*f).to_owned()).collect(),
limits: Some(v1::Limits {
max_message_chars: 1024,
max_page: 100,
// HOME, SERVER and LIVE, and the chats.
max_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS + 3,
max_chat_subscriptions: driver::MAX_CHAT_SUBSCRIPTIONS,
max_live_subscriptions: 8,
..Default::default()
}),
time_ms: now_ms(),
..Default::default()
};
let (cmds_tx, cmds_rx) = mpsc::unbounded_channel();
let own_slot = Arc::new(AtomicU32::new(entities::slot(joined.own_client)));
let (pushes_tx, pushes_rx) = mpsc::channel(params.push_capacity.max(16));
let (closed_tx, closed_rx) = watch::channel(None);
let (port, streams) = if joined.capabilities.streams {
let (events_tx, events_rx) = mpsc::unbounded_channel();
let cmds = cmds_tx.clone();
let send = move |cmd| {
let _ = cmds.send(Cmd::Stream(cmd));
};
(Some(events_tx), Some(StreamPort::new(send, events_rx)))
} else {
(None, None)
};
let details = ServerDetails { uid: Some(joined.server_uid.clone()), ..Default::default() };
let driver = Driver::new(Parts {
cfg: Config {
ts6,
own_client: joined.own_client,
nickname,
own_uid: joined.own_uid.clone(),
files: joined.capabilities.file_transfer,
mail: joined.capabilities.offline_messages,
},
inner: inner_tx,
events,
early,
bus,
engine_bus: ctx.link.events.clone(),
pushes: pushes_tx,
media: params.media.clone(),
port,
closed: closed_tx,
own_slot: own_slot.clone(),
server: entities::server(&details, &joined.name, 0),
epoch: u64::try_from(now_ms()).unwrap_or(1).max(1),
});
let session = LinkSession {
welcome,
features: Features::new(features),
cmds: cmds_tx,
closed: closed_rx,
own_slot,
};
tokio::spawn(driver.run(cmds_rx));
Ok(LocalConnected {
connected: Connected {
session: Arc::new(session),
pushes: pushes_rx,
// A TeamSpeak server has no host key to pin.
host_uid: [0; 32],
},
streams,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::link::{Backends, VoiceOptions, connect_params};
use voelin_proto::link::IssuerTrust;
fn params(options: &VoiceOptions) -> ConnectParams {
let (media, _rx) = voelin_proto::test_util::media_channel();
connect_params(options, media, &Backends::empty()).unwrap()
}
fn back(options: &VoiceOptions) -> ConnectOptions {
inner_options(&params(options), &LocalCtx::standalone()).unwrap()
}
#[test]
fn the_options_of_a_bookmark_come_back_as_they_went() {
let mut options = VoiceOptions::new("ts.example.com:9988", "nick");
let same = back(&options);
assert_eq!(
(same.address.as_str(), same.nickname.as_str()),
("ts.example.com:9988", "nick")
);
assert!(same.identity.is_none() && same.client_version.is_none());
assert!(same.channel.is_none() && same.server_password.is_none() && same.token.is_none());
// Everything a connection can be told: the server password and the
// privilege key go in the hello, the channel and its password in the
// link, the identity as a credential.
options.server_password = Some("s3cret pass&word".into());
options.channel = Some("Games/Raid Night".into());
options.channel_password = Some("p w+%".into());
options.token = Some("tokenvalue".into());
let identity = tsclientlib::Identity::create();
options.identity = Some(crate::ts::identity::to_blob(&identity));
// A spec the user can give; the connector resolves it.
options.client_version = Some("generic".into());
options.audio = false;
let sent = params(&options);
assert_eq!(sent.hello.password, "s3cret pass&word");
assert_eq!(sent.hello.invite_code, "tokenvalue");
assert_eq!(sent.hello.nickname, "nick");
assert!(
sent.address.starts_with("ts3server://ts.example.com?port=9988"),
"{}",
sent.address
);
assert!(!sent.address.contains("s3cret") && !sent.address.contains("tokenvalue"));
let got = back(&options);
assert_eq!(got.address, "ts.example.com:9988");
assert_eq!(got.server_password, options.server_password);
assert_eq!(got.channel.as_deref(), Some("Games/Raid Night"));
assert_eq!(got.channel_password, options.channel_password);
assert_eq!(got.token.as_deref(), Some("tokenvalue"));
assert_eq!(got.client_version, versions::resolve("generic").unwrap());
assert!(got.client_version.is_some());
// The identity is the same key and counters.
let b = got.identity.as_ref().unwrap();
assert_eq!(serde_json::to_value(&identity).unwrap(), serde_json::to_value(b).unwrap());
}
#[test]
fn a_channel_by_id_and_an_address_that_is_a_link_are_kept() {
let mut options = VoiceOptions::new("[::1]:9987", "nick");
options.channel = Some("/12".into());
let got = back(&options);
assert_eq!(got.address, "[::1]:9987");
assert_eq!(got.channel.as_deref(), Some("/12"));
// A bookmark that is a link keeps its own parameters.
let options = VoiceOptions::new("ts3server://ts.example.com?port=1&channel=Lobby", "nick");
let got = back(&options);
assert_eq!(
(got.address.as_str(), got.channel.as_deref()),
("ts.example.com:1", Some("Lobby"))
);
// Another scheme is left as it is for the connector of that scheme.
let options = VoiceOptions::new("voelin://host/i/code", "nick");
assert_eq!(params(&options).address, "voelin://host/i/code");
}
#[test]
fn what_is_no_teamspeak_identity_is_refused() {
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential = Credential::Voelin(Arc::new(voelin_proto::test_util::FakeSigner));
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
assert!(matches!(error, SessionError::Protocol(_)));
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential =
Credential::Account { kind: "teamspeak", integration_id: Bytes::from_static(b"id") };
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential =
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(b"not json") };
assert!(inner_options(&sent, &LocalCtx::standalone()).is_err());
// A host that wants trust is refused: TeamSpeak has no host key.
let backends = Backends::empty();
let confirm = backends.trust().confirm(voelin_proto::link::HostIdentity {
address: "x".into(),
uid: [0; 32],
previous: None,
});
assert!(!futures::executor::block_on(confirm));
}
/// An identity that cannot be read ends the connect with words that say
/// where it is wrong and hold none of the key: the JSON reader's own
/// message quotes a key that does not import, and this text reaches the
/// event bus and the status line.
#[test]
fn an_identity_that_cannot_be_read_is_refused_without_the_key() {
let (json, cut) = identity::json_with_a_cut_key();
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
sent.credential = Credential::Foreign { kind: "teamspeak", blob: Bytes::from(json) };
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
assert!(
text.starts_with(
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
),
"{text}"
);
identity::assert_holds_no_piece_of(&text, &cut);
// Not even text.
sent.credential =
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(&[b'{', 0xff]) };
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
assert_eq!(text, "the TeamSpeak identity cannot be read: it is not text");
}
#[test]
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
let sent = params(&VoiceOptions::new("ts.example.com", "nick"));
assert!(sent.account.is_none());
assert_eq!(sent.issuer_trust, IssuerTrust::Unknown);
assert!(sent.linked.is_empty() && sent.host_pin.is_none());
assert_eq!((sent.push_capacity, sent.timeout), (1024, Duration::from_secs(35)));
let client = sent.hello.client.unwrap();
assert_eq!(client.name, "Voelin");
assert_eq!(sent.hello.version, 1);
}
/// Why `connect_params` refused an address, if it did.
fn refused(address: &str) -> Option<String> {
let (media, _rx) = voelin_proto::test_util::media_channel();
match connect_params(&VoiceOptions::new(address, "nick"), media, &Backends::empty()) {
Ok(_) => None,
Err(SessionError::Protocol(text)) => Some(text),
Err(other) => panic!("{address}: {other}"),
}
}
#[test]
fn a_bookmark_the_link_would_change_is_refused() {
// A port that is no port, in any shape: the link would drop it and the
// connection would go to the default port.
for address in [
"ts.example.com:99999",
"ts.example.com:65536",
"ts.example.com:0",
"ts.example.com:abc",
"ts.example.com:",
"[::1]:70000",
"[::1]:",
"[::1]x",
] {
let text = refused(address).unwrap_or_else(|| panic!("{address} was accepted"));
assert!(text.contains("65535") && text.contains(address), "{text}");
}
// A host the link would cut or decode: a `?` hides the channel behind the
// next one, a `/` or `#` ends the host, a `%` is decoded.
for address in [
"",
" ",
"ts.example.com?x",
"ts.example.com#x",
"ts.example.com/x",
"a b",
"h%41",
"[::1",
] {
let text = refused(address).unwrap_or_else(|| panic!("{address:?} was accepted"));
assert!(text.starts_with("not a server address"), "{text}");
}
// The text names no query: a link keeps secrets in it.
let text = refused("ts.example.com?password=hunter2").unwrap();
assert!(!text.contains("hunter2"), "{text}");
}
#[test]
fn the_bookmarks_a_server_has_come_back_with_their_channel() {
for (address, host) in [
("ts.example.com", "ts.example.com"),
("ts.example.com:9987", "ts.example.com:9987"),
(" ts.example.com:1 ", "ts.example.com:1"),
("127.0.0.1:65535", "127.0.0.1:65535"),
("[::1]:9987", "[::1]:9987"),
// The brackets of a v6 address without a port are the link's to drop;
// the TeamSpeak library reads both forms.
("[::1]", "::1"),
("::1", "::1"),
("2001:db8::1", "2001:db8::1"),
] {
let mut options = VoiceOptions::new(address, "nick");
options.channel = Some("Games/Raid".into());
let got = back(&options);
assert_eq!((got.address.as_str(), got.channel.as_deref()), (host, Some("Games/Raid")));
}
}
/// The normalisations of the round trip, listed in `docs/session-seam.md`
/// (13): an empty option is none, and an empty nickname stays empty.
#[test]
fn empty_options_come_back_as_none() {
let mut options = VoiceOptions::new("ts.example.com", "");
options.server_password = Some(String::new());
options.channel = Some(String::new());
options.channel_password = Some(String::new());
options.token = Some(String::new());
let got = back(&options);
assert!(got.nickname.is_empty());
assert!(
got.server_password.is_none()
&& got.channel.is_none()
&& got.channel_password.is_none()
&& got.token.is_none()
);
}
}
@@ -8,7 +8,7 @@ use anyhow::{Context, Result, bail};
use base64::prelude::*;
use tsclientlib::Version;
const VERSIONS_CSV: &str = include_str!("../../proto/tsproto-structs/declarations/Versions.csv");
const VERSIONS_CSV: &str = include_str!("../../../proto/tsproto-structs/declarations/Versions.csv");
/// The signed generic version of every platform, tsclientlib's default.
const GENERIC_VERSION: &str = "3.?.? [Build: 5680278000]";
@@ -1,5 +1,5 @@
//! The TeamSpeak link: a normal client connection ([`crate::TsLink`] runs
//! [`run`]).
//! The TeamSpeak connection: a normal client connection
//! ([`TsLink`](super::ts_link::TsLink) runs [`run`]).
//!
//! Besides presence, chat, voice and stream signalling it carries what only
//! a client connection can do: pokes, file transfer (channel files,
@@ -14,14 +14,12 @@
//! gateway directory, our own stream's life ([`LinkEvent::OwnStream`]).
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use base64::Engine as _;
use futures::prelude::*;
use tokio::sync::{mpsc, watch};
use tokio::task::AbortHandle;
use tokio::sync::{mpsc, oneshot, watch};
use tokio::time::{Instant, timeout};
use tracing::{debug, info, warn};
use tsclientlib::events::Event as BookEvent;
@@ -36,12 +34,11 @@ use voelin_audio::{EncodedVoice, TalkerId, VoiceCodec, VoicePacket};
use voelin_model::{Capabilities, ChannelId, ChatMessage, ChatTarget, ServerFlavor};
use voelin_stream::{ClientState, Request, StreamNotification};
use crate::book::presence_from_book;
use crate::cache;
use crate::files::{self, FileEntry, Report, RequestId, Sink, TransferId, TransferState};
use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, Remote};
use super::book::presence_from_book;
use super::ts_link::{ConnectOptions, Watches};
use crate::files::{self, FileEntry, RequestId, TransferState};
use crate::link::{BoxDuplex, BoxRead, LinkCmd, LinkCtx, LinkEvent, Remote};
use crate::offline::{OfflineMessage, OfflineMessageInfo};
use crate::settings::FILES_PROGRESS_MS;
use crate::stream::{StreamCmd, StreamHandle, StreamInput};
use crate::{BackendInfo, Event, JoinFailure, POKE_MESSAGE_MAX};
@@ -157,74 +154,39 @@ enum Pending {
Quiet,
}
/// A transfer the server has not opened yet.
/// A transfer connection the server has not opened yet: the caller wants the
/// connection itself, and does the copying (the engine's `SessionLink`
/// does, with its progress, its limits and its cancel).
enum Job {
Download {
transfer: Option<TransferId>,
offset: u64,
sink: Sink,
report: Report,
started: Instant,
},
Upload {
transfer: Option<TransferId>,
from: PathBuf,
size: u64,
report: Report,
},
/// [`LinkCmd::OpenRead`].
OpenRead(oneshot::Sender<Result<(u64, BoxRead), String>>),
/// [`LinkCmd::OpenWrite`].
OpenWrite(oneshot::Sender<Result<(u64, BoxDuplex), String>>),
}
impl Job {
fn report(&self) -> &Report {
/// The job could not be done: tell whoever waits.
fn fail(self, text: String) {
match self {
Job::Download { report, .. } | Job::Upload { report, .. } => report,
Job::OpenRead(reply) => {
let _ = reply.send(Err(text));
}
Job::OpenWrite(reply) => {
let _ = reply.send(Err(text));
}
}
}
fn transfer(&self) -> Option<TransferId> {
match self {
Job::Download { transfer, .. } | Job::Upload { transfer, .. } => *transfer,
}
}
}
/// How long a picture of `size` bytes may take to arrive: a minute, plus
/// its size at [`cache::MIN_PICTURE_RATE`], so large banners arrive on slow
/// links while a stalled transfer still ends.
fn image_download_time(size: u64) -> Duration {
Duration::from_secs(60 + size / cache::MIN_PICTURE_RATE)
}
/// How long the server may take to start an image transfer (a busy server
/// answers the requests of a large channel tree in turn).
const IMAGE_NEGOTIATION: Duration = Duration::from_secs(30);
/// Bound background image handshakes without imposing a deadline on user transfers.
fn expire_image_jobs(jobs: &mut HashMap<FiletransferHandle, Job>, now: Instant) {
jobs.retain(|_, job| {
if matches!(job, Job::Download { transfer: None, started, .. } if now.duration_since(*started) >= IMAGE_NEGOTIATION) {
job.report()(TransferState::Failed("image transfer negotiation timed out".into()));
false
} else {
true
}
});
}
/// A user's transfer, for cancelling.
enum Slot {
Waiting(FiletransferHandle),
Running { task: AbortHandle, part: Option<PathBuf>, report: Report },
}
/// Run a voice connection until it ends or is told to disconnect.
pub(crate) async fn run(
options: ConnectOptions,
ctx: LinkCtx,
account: Watches,
mut commands: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
let reason = match run_inner(&options, ctx, &mut commands, &events).await {
let reason = match run_inner(&options, ctx, account, &mut commands, &events).await {
Ok(()) => None,
Err(e) => Some(e.to_string()),
};
@@ -254,13 +216,14 @@ impl Drop for ConnectionStreams {
struct Voice {
con: Connection,
link: LinkCtx,
/// The account this connection presents (and keeps open).
account: Watches,
events: mpsc::UnboundedSender<LinkEvent>,
server_uid: String,
/// Who is talking: last voice packet per client.
talking: HashMap<u16, Instant>,
pending: HashMap<MessageHandle, Pending>,
jobs: HashMap<FiletransferHandle, Job>,
transfers: HashMap<TransferId, Slot>,
/// `updatemytsdata` is to be sent once connected again: a reconnect
/// (tsclientlib's own) leaves the server without it.
myts_data_due: bool,
@@ -276,17 +239,18 @@ struct Voice {
async fn run_inner(
options: &ConnectOptions,
link: LinkCtx,
account: Watches,
commands: &mut mpsc::UnboundedReceiver<LinkCmd>,
events: &mpsc::UnboundedSender<LinkEvent>,
) -> anyhow::Result<()> {
let version = match &options.client_version {
Some(version) => version.clone(),
None => crate::versions::native_version()?,
None => super::versions::native_version()?,
};
let mut builder = Connection::build(options.address.clone())
.name(options.nickname.clone())
.version(version)
.metadata(crate::versions::client_metadata());
.metadata(super::versions::client_metadata());
if let Some(identity) = &options.identity {
builder = builder.identity(identity.clone());
}
@@ -302,8 +266,8 @@ async fn run_inner(
if let Some(token) = &options.token {
builder = builder.default_token(token.clone());
}
let mut identity = link.myts_identity.clone();
let mut data = link.myts_data.clone();
let mut identity = account.identity.clone();
let mut data = account.data.clone();
// A changed account invalidates an in-flight handshake. Drop that connection
// and take a fresh snapshot before publishing any connected state.
let mut con = timeout(Duration::from_secs(30), async {
@@ -385,12 +349,12 @@ async fn run_inner(
let mut voice = Voice {
con,
link,
account,
events: events.clone(),
server_uid,
talking: HashMap::new(),
pending: HashMap::new(),
jobs: HashMap::new(),
transfers: HashMap::new(),
myts_data_due: false,
myts_shown: tsclientlib::MytsData::default(),
streams,
@@ -468,7 +432,7 @@ async fn run_inner(
drop(voice.streams.take());
// Transfers the server never opened fail; running ones go on.
for (_, job) in voice.jobs.drain() {
job.report()(TransferState::Failed("disconnected".into()));
job.fail("disconnected".into());
}
let disconnect = shutdown_connection(voice.con).await;
result?;
@@ -552,7 +516,6 @@ impl Voice {
}
fn tick(&mut self) {
expire_image_jobs(&mut self.jobs, Instant::now());
let events = &self.events;
self.talking.retain(|client, last| {
let active = last.elapsed() < Duration::from_millis(400);
@@ -563,10 +526,6 @@ impl Voice {
});
}
fn progress_every(&self) -> Duration {
Duration::from_millis(self.link.settings.current().get(&FILES_PROGRESS_MS).into())
}
fn item(&mut self, item: StreamItem) -> anyhow::Result<()> {
match item {
StreamItem::BookEvents(book_events) => {
@@ -605,60 +564,25 @@ impl Voice {
}
}
}
// The server opened a transfer connection: the caller that asked for it
// gets the connection itself.
StreamItem::FileDownload(handle, download) => {
if let Some(Job::Download { transfer, offset, sink, report, .. }) =
self.jobs.remove(&handle)
if matches!(self.jobs.get(&handle), Some(Job::OpenRead(_)))
&& let Some(Job::OpenRead(reply)) = self.jobs.remove(&handle)
{
// Pictures (avatars, icons, banners): bounded like the
// banners on the web, the user's own files are not.
if transfer.is_none() && download.size > cache::MAX_PICTURE_BYTES {
let limit = cache::MAX_PICTURE_BYTES >> 20;
report(TransferState::Failed(format!("larger than {limit} MiB")));
return Ok(());
}
let part = sink.part().map(ToOwned::to_owned);
let progress = self.progress_every();
let task_report = report.clone();
let deadline = image_download_time(download.size);
let task = tokio::spawn(async move {
let receive = files::download(
download.stream,
download.size,
offset,
sink,
progress,
task_report.clone(),
);
if transfer.is_some() {
receive.await;
} else if timeout(deadline, receive).await.is_err() {
task_report(TransferState::Failed("image download timed out".into()));
}
});
self.running(transfer, task.abort_handle(), part, report);
let _ = reply.send(Ok((download.size, Box::pin(download.stream))));
}
}
StreamItem::FileUpload(handle, upload) => {
if let Some(Job::Upload { transfer, from, size, report }) =
self.jobs.remove(&handle)
if matches!(self.jobs.get(&handle), Some(Job::OpenWrite(_)))
&& let Some(Job::OpenWrite(reply)) = self.jobs.remove(&handle)
{
let task = tokio::spawn(files::upload(
upload.stream,
from,
size,
upload.seek_position,
self.progress_every(),
report.clone(),
));
self.running(transfer, task.abort_handle(), None, report);
let _ = reply.send(Ok((upload.seek_position, Box::pin(upload.stream))));
}
}
StreamItem::FiletransferFailed(handle, error) => {
if let Some(job) = self.jobs.remove(&handle) {
if let Some(id) = job.transfer() {
self.transfers.remove(&id);
}
job.report()(TransferState::Failed(transfer_error(&error)));
job.fail(transfer_error(&error));
}
}
StreamItem::DisconnectedTemporarily(reason) => {
@@ -672,22 +596,6 @@ impl Voice {
Ok(())
}
fn running(
&mut self,
transfer: Option<TransferId>,
task: AbortHandle,
part: Option<PathBuf>,
report: Report,
) {
self.transfers.retain(|_, slot| match slot {
Slot::Running { task, .. } => !task.is_finished(),
Slot::Waiting(_) => true,
});
if let Some(id) = transfer {
self.transfers.insert(id, Slot::Running { task, part, report });
}
}
/// A chat message or poke from the book.
fn message(&self, target: &MessageTarget, invoker: &tsclientlib::Invoker, text: &str) {
let uid = invoker.uid.as_ref().map(|u| u.as_ref().to_string());
@@ -868,8 +776,8 @@ impl Voice {
/// gave, when it is for the myTS ID this connection presents; nothing
/// without one (signed out).
fn myts_wanted(&self) -> tsclientlib::MytsData {
let identity = self.link.myts_identity.borrow();
let data = self.link.myts_data.borrow();
let identity = self.account.identity.borrow();
let data = self.account.data.borrow();
match (identity.as_deref(), data.as_deref()) {
(Some(identity), Some(data)) if data.myts_id == identity.id_bytes() => data.clone(),
_ => tsclientlib::MytsData::default(),
@@ -1069,72 +977,40 @@ impl Voice {
Pending::FileList { request, channel: dir.channel, path, entries: Vec::new() };
self.send(cmd, pending)?;
}
LinkCmd::Download { transfer, file, sink, report } => {
let offset = sink.offset();
LinkCmd::OpenRead { file, offset, reply } => {
let seek = (offset > 0).then_some(offset);
let password = file.password.as_deref().filter(|p| !p.is_empty());
let channel = tsclientlib::ChannelId(file.channel);
let handle = match self.con.download_file(channel, &file.path, password, seek) {
Ok(handle) => handle,
match self.con.download_file(channel, &file.path, password, seek) {
Ok(handle) => {
self.jobs.insert(handle, Job::OpenRead(reply));
}
Err(e) => {
report(TransferState::Failed(e.to_string()));
return Ok(());
let _ = reply.send(Err(e.to_string()));
}
};
report(TransferState::Requested);
self.jobs.insert(
handle,
Job::Download { transfer, offset, sink, report, started: Instant::now() },
);
if let Some(id) = transfer {
self.transfers.insert(id, Slot::Waiting(handle));
}
}
LinkCmd::Upload { transfer, file, from, overwrite, resume, report } => {
let size = match std::fs::metadata(&from) {
Ok(m) if m.is_file() => m.len(),
Ok(_) => {
report(TransferState::Failed(format!("{} is not a file", from.display())));
return Ok(());
}
Err(e) => {
report(TransferState::Failed(format!("{}: {e}", from.display())));
return Ok(());
}
};
LinkCmd::OpenWrite { file, size, overwrite, resume, reply } => {
let password = file.password.as_deref().filter(|p| !p.is_empty());
let channel = tsclientlib::ChannelId(file.channel);
let handle = match self
.con
.upload_file(channel, &file.path, password, size, overwrite, resume)
{
Ok(handle) => handle,
match self.con.upload_file(channel, &file.path, password, size, overwrite, resume) {
Ok(handle) => {
self.jobs.insert(handle, Job::OpenWrite(reply));
}
Err(e) => {
report(TransferState::Failed(e.to_string()));
return Ok(());
let _ = reply.send(Err(e.to_string()));
}
};
report(TransferState::Requested);
self.jobs.insert(handle, Job::Upload { transfer, from, size, report });
if let Some(id) = transfer {
self.transfers.insert(id, Slot::Waiting(handle));
}
}
LinkCmd::CancelTransfer(id) => match self.transfers.remove(&id) {
Some(Slot::Waiting(handle)) => {
if let Some(job) = self.jobs.remove(&handle) {
job.report()(TransferState::Cancelled);
}
}
Some(Slot::Running { task, part, report }) if !task.is_finished() => {
task.abort();
if let Some(part) = part {
let _ = std::fs::remove_file(part);
}
report(TransferState::Cancelled);
}
_ => debug!(id, "cancel: no such transfer (finished?)"),
},
// SessionLink copies the bytes itself, over the connections OpenRead and
// OpenWrite open (`docs/session-seam.md` section 8): this link is never
// given a transfer to run. One that is given anyway fails (its report
// is the answer), and the connection, which other things ride on, goes
// on; there is nothing to cancel.
LinkCmd::Download { report, .. } | LinkCmd::Upload { report, .. } => {
report(TransferState::Failed("this link does not run transfers itself".into()));
}
LinkCmd::CancelTransfer(id) => debug!(transfer = id, "no transfer runs on this link"),
LinkCmd::DeleteFiles { request, channel, password, paths } => {
let cpw = encode_password(password.as_deref());
let mut parts = paths.iter().map(|p| c2s::OutDeleteFilePart {
@@ -1499,52 +1375,6 @@ mod poke_tests {
}
}
#[cfg(test)]
mod image_download_tests {
use super::*;
use std::sync::{Arc, Mutex};
#[test]
fn stalled_image_handshake_expires_but_user_transfer_does_not() {
let started = Instant::now();
let reports = Arc::new(Mutex::new(Vec::new()));
let sink = reports.clone();
let report: Report = Arc::new(move |state| sink.lock().unwrap().push(state));
let mut jobs = HashMap::new();
for (id, transfer) in [(1, None), (2, Some(77))] {
jobs.insert(
FiletransferHandle(id),
Job::Download {
transfer,
offset: 0,
sink: Sink::Memory,
report: report.clone(),
started,
},
);
}
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION - Duration::from_secs(1));
assert_eq!(jobs.len(), 2);
assert!(reports.lock().unwrap().is_empty());
expire_image_jobs(&mut jobs, started + IMAGE_NEGOTIATION);
assert_eq!(jobs.len(), 1);
assert!(jobs.contains_key(&FiletransferHandle(2)));
assert!(
matches!(&reports.lock().unwrap()[..], [TransferState::Failed(error)] if error.contains("timed out"))
);
expire_image_jobs(&mut jobs, started + Duration::from_secs(60));
assert_eq!(reports.lock().unwrap().len(), 1);
}
#[test]
fn large_pictures_get_time_to_arrive() {
assert_eq!(image_download_time(0), Duration::from_secs(60));
assert_eq!(image_download_time(100 << 10), Duration::from_secs(72));
// The largest picture, at the slowest rate allowed.
assert_eq!(image_download_time(cache::MAX_PICTURE_BYTES), Duration::from_secs(60 + 16384));
}
}
#[cfg(test)]
mod account_tests {
use super::*;
@@ -1678,18 +1508,20 @@ mod account_tests {
events,
frames: broadcast::channel(1).0,
settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()),
myts_identity: watch::channel(Some(Arc::new(identity))).1,
myts_data: watch::channel(Some(Arc::new(data))).1,
};
let account = Watches::of(
watch::channel(Some(Arc::new(identity))).1,
watch::channel(Some(Arc::new(data))).1,
);
Voice {
con: Connection::build(server.local_addr().unwrap().to_string()).connect().unwrap(),
link,
account,
events: mpsc::unbounded_channel().0,
server_uid: String::new(),
talking: HashMap::new(),
pending: HashMap::new(),
jobs: HashMap::new(),
transfers: HashMap::new(),
myts_data_due: false,
myts_shown: tsclientlib::MytsData::default(),
streams: None,
@@ -1731,7 +1563,7 @@ mod account_tests {
let other = unconnected(&server, account_data(&[2; 33]));
assert_eq!(other.myts_wanted(), tsclientlib::MytsData::default());
let mut signed_out = unconnected(&server, account_data(&[1; 33]));
signed_out.link.myts_identity = watch::channel(None).1;
signed_out.account.identity = watch::channel(None).1;
assert_eq!(signed_out.myts_wanted(), tsclientlib::MytsData::default());
for voice in [voice, other, signed_out] {
timeout(Duration::from_millis(100), shutdown_connection(voice.con))
@@ -1741,6 +1573,46 @@ mod account_tests {
}
}
/// `SessionLink` copies the bytes of a transfer itself. A transfer command
/// that reaches this link anyway fails that transfer with its report, and
/// not the connection, which every other request of the session rides on.
#[tokio::test]
async fn a_transfer_command_fails_the_transfer_and_not_the_connection() {
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
let mut voice = unconnected(&server, account_data(&[1; 33]));
let states = Arc::new(std::sync::Mutex::new(Vec::new()));
let report: crate::files::Report = {
let states = states.clone();
Arc::new(move |state| states.lock().unwrap().push(state))
};
let file = || Remote { channel: 1, password: None, path: "/a".into() };
let kept = "the connection goes on";
voice
.command(LinkCmd::Download {
transfer: Some(1),
file: file(),
sink: crate::files::Sink::Memory,
report: report.clone(),
})
.expect(kept);
voice
.command(LinkCmd::Upload {
transfer: None,
file: file(),
from: "a".into(),
overwrite: false,
resume: false,
report,
})
.expect(kept);
// Nothing runs, so there is nothing to cancel and nobody to tell.
voice.command(LinkCmd::CancelTransfer(1)).expect(kept);
let failed = TransferState::Failed("this link does not run transfers itself".into());
assert_eq!(*states.lock().unwrap(), [failed.clone(), failed]);
assert!(voice.jobs.is_empty() && voice.pending.is_empty());
timeout(Duration::from_millis(100), shutdown_connection(voice.con)).await.unwrap().unwrap();
}
#[tokio::test]
async fn shutdown_never_polls_a_connecting_connection() {
let server = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
@@ -1766,20 +1638,22 @@ mod account_tests {
events,
frames: broadcast::channel(1).0,
settings: crate::settings::SharedSettings::new(crate::settings::Settings::default()),
myts_identity: identity,
myts_data: watch::channel(None).1,
};
let watches = Watches::of(identity, watch::channel(None).1);
let (_commands, commands) = mpsc::unbounded_channel();
let (events, mut received) = mpsc::unbounded_channel();
let task = tokio::spawn(run(
ConnectOptions::new(server.local_addr().unwrap().to_string(), "account-test"),
link,
watches,
commands,
events,
));
let mut packet = [0; 2048];
let (_, first) =
timeout(Duration::from_secs(5), server.recv_from(&mut packet)).await.unwrap().unwrap();
let (_, first) = timeout(Duration::from_secs(5), server.recv_from(&mut packet))
.await
.expect("the first handshake packet within 5 s")
.unwrap();
// A logout/clear notification must cancel the old socket and restart.
account.send_replace(None);
let second = timeout(Duration::from_secs(5), async {
@@ -1791,11 +1665,14 @@ mod account_tests {
}
})
.await
.unwrap();
.expect("a handshake packet from a new socket within 5 s of the account change");
assert_ne!(first, second);
// Losing the account authority fails closed immediately, not after connect timeout.
drop(account);
timeout(Duration::from_secs(2), task).await.unwrap().unwrap();
timeout(Duration::from_secs(2), task)
.await
.expect("the connection to end within 2 s of the account source closing")
.unwrap();
assert!(
matches!(received.recv().await, Some(LinkEvent::Disconnected(Some(reason))) if reason == "account source closed")
);
-34
View File
@@ -1,34 +0,0 @@
//! [`TsLink`]: the TeamSpeak implementation of [`ServerLink`].
//!
//! It connects as a normal TeamSpeak 3 or 6 client with `tsclientlib` and
//! runs the connection ([`crate::voice`]) with everything that rides on it:
//! chat, voice, files, pokes, offline messages and, on TeamSpeak 6, the
//! stream task. Which product the server is (and what it can do) is decided
//! there, from the version it sends, and reported in
//! [`LinkEvent::Connected`](crate::link::LinkEvent::Connected).
//!
//! Everything it uses (`voice.rs`, `book.rs`, `stream.rs`, `versions.rs`,
//! `identity.rs`) is TeamSpeak's and leaves this crate together with it:
//! the plan moves `TsLink` into the TeamSpeak gateway, `voelin-gateway-ts`
//! of VoelinGateWay.
use tokio::sync::mpsc;
use crate::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink};
use crate::voice;
/// Connects to TeamSpeak 3 and 6 servers. The engine's default link.
#[derive(Clone, Copy, Debug, Default)]
pub struct TsLink;
impl ServerLink for TsLink {
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
tokio::spawn(voice::run(options, ctx, cmds, events));
}
}
+71 -10
View File
@@ -960,11 +960,27 @@ pub(crate) mod tests {
/// What `f` logs at info (and above) on this thread: each line its
/// message, then its fields (` name=value`).
///
/// One recording subscriber is installed for the whole test process, the
/// first time this is called, and each call records into a buffer of its
/// own thread. A scoped one (`tracing::subscriber::with_default`) loses
/// lines: while it is the only subscriber alive, a callsite that another
/// test's thread meets first is registered against that thread's own
/// default, which is none, and stays disabled for every thread, so the
/// lines of the test that reads them are gone
/// (`session::banner_tests::a_failing_banner_is_logged_once_with_its_address`
/// failed with no lines at all, once in about thirty runs of the suite).
pub(crate) fn info_lines<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
use std::cell::RefCell;
use std::sync::Once;
use tracing::field::{Field, Visit};
use tracing::span;
struct Lines(Arc<Mutex<Vec<String>>>);
thread_local! {
/// The lines of the `info_lines` running on this thread, if any.
static LINES: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
}
#[derive(Default)]
struct Line(String, String);
impl Visit for Line {
@@ -975,7 +991,8 @@ pub(crate) mod tests {
}
}
}
impl tracing::Subscriber for Lines {
struct Recorder;
impl tracing::Subscriber for Recorder {
fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool {
*metadata.level() <= tracing::Level::INFO
}
@@ -985,19 +1002,57 @@ pub(crate) mod tests {
fn record(&self, _: &span::Id, _: &span::Record<'_>) {}
fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
fn event(&self, event: &tracing::Event<'_>) {
let mut line = Line::default();
event.record(&mut line);
self.0.lock().unwrap().push(line.0 + &line.1);
LINES.with(|lines| {
if let Some(lines) = lines.borrow_mut().as_mut() {
let mut line = Line::default();
event.record(&mut line);
lines.push(line.0 + &line.1);
}
});
}
fn enter(&self, _: &span::Id) {}
fn exit(&self, _: &span::Id) {}
}
let lines = Arc::new(Mutex::new(Vec::new()));
let result = tracing::subscriber::with_default(Lines(lines.clone()), f);
let lines = lines.lock().unwrap().clone();
/// Ends the recording of this thread, also when `f` panics.
struct Recording;
impl Drop for Recording {
fn drop(&mut self) {
LINES.with(|lines| lines.borrow_mut().take());
}
}
static INSTALL: Once = Once::new();
INSTALL.call_once(|| {
tracing::subscriber::set_global_default(Recorder)
.expect("no other global tracing subscriber in the tests");
// Makes every callsite decide again with the subscriber in place, also
// one that a thread was registering while it was being installed
// (creating a `Dispatch` rebuilds the cached interest of all of them).
drop(tracing::Dispatch::new(Recorder));
});
LINES.with(|lines| *lines.borrow_mut() = Some(Vec::new()));
let _recording = Recording;
let result = f();
let lines = LINES.with(|lines| lines.borrow_mut().take().unwrap_or_default());
(result, lines)
}
/// The lines of `info_lines` do not depend on which thread met a callsite
/// first: this one is met on another thread, which records nothing, before
/// the thread that reads the lines meets it.
#[test]
fn info_lines_see_a_callsite_another_thread_met_first() {
fn log() {
tracing::info!("met");
}
let ((), lines) = info_lines(|| {
std::thread::spawn(log).join().unwrap();
log();
});
assert_eq!(lines, ["met"]);
}
fn temp_dir(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("voelin-web-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
@@ -1375,9 +1430,15 @@ pub(crate) mod tests {
};
let mut port = [0u8; 2];
client.read_exact(&mut port).await.unwrap();
let target = format!("{host}:{}", u16::from_be_bytes(port));
let port = u16::from_be_bytes(port);
let target = format!("{host}:{port}");
targets.send(target.clone()).unwrap();
let mut server = TcpStream::connect(target).await.unwrap();
// The proxy resolves the name it is given (SOCKS5h). `localhost` is
// 127.0.0.1 to it, whatever this machine's resolver says: some answer
// `::1` only, and the servers of the tests listen on 127.0.0.1.
let dial =
if host == "localhost" { format!("127.0.0.1:{port}") } else { target };
let mut server = TcpStream::connect(dial).await.unwrap();
client.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0]).await.unwrap();
let _ = tokio::io::copy_bidirectional(&mut client, &mut server).await;
});
+28
View File
@@ -0,0 +1,28 @@
//! What more than one integration test of this crate needs (a test binary
//! that uses it declares `mod common;`).
use std::path::{Path, PathBuf};
use std::time::Duration;
/// Wait until nothing has the SQLite database at `path` open any more, as when
/// the process that had it has ended: SQLite deletes the write-ahead log
/// (`<path>-wal`) when the last connection closes.
///
/// A dropped `Engine` is not that yet. Its task ends later, the history writer
/// is joined there, and closing the connection checkpoints the log under an
/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the
/// lock only as long as the busy timeout (5 s) and then fails with
/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking
/// 6 s it happens every time).
pub async fn closed(path: &Path) {
let mut wal = path.as_os_str().to_owned();
wal.push("-wal");
let wal = PathBuf::from(wal);
tokio::time::timeout(Duration::from_secs(120), async {
while wal.exists() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the engine's database connection closed");
}
+59 -6
View File
@@ -16,6 +16,7 @@ use tokio_tungstenite::tungstenite::handshake::server::{Request, Response};
use voelin_core::gateway::{GatewayRequest, GatewayUpdate};
use voelin_core::history::MessageSource;
use voelin_core::settings::Settings;
use voelin_core::ts::identity::to_blob;
use voelin_core::{Command, Engine, Event, History, HistoryMessage, HistorySource, ObserveState};
use voelin_gateway_proto::{
ClientMsg, Envelope, ErrorCode, HistoryEntry, HistoryPage, PinInfo, ReactionCount, ServerMsg,
@@ -23,6 +24,8 @@ use voelin_gateway_proto::{
};
use voelin_model::{ChatMessage, ChatTarget, PresenceSnapshot};
mod common;
const LOBBY: ChatTarget = ChatTarget::Channel(1);
const ME: &str = "me-uid";
@@ -448,7 +451,7 @@ fn observe(engine: &Engine, session: u64, gw: &FakeGateway) {
engine.send(Command::ObserveGateway {
session,
urls: vec![gw.url.clone()],
identity: Box::new(identity),
identity: Box::new(to_blob(&identity)),
});
}
@@ -528,6 +531,8 @@ async fn history_on_open_paging_and_offline_messages() {
assert_eq!(texts(&stored), ["m1", "m2", "m3", "m4", "m5", "while away 1", "while away 2"]);
history.flush();
drop((engine, history));
// Dropping the engine does not close the database yet (see `closed`).
common::closed(&path).await;
// After a restart, with the gateway down: the stored page, found by the
// gateway's URL, which is remembered with the server's id.
@@ -742,7 +747,7 @@ async fn an_unreachable_gateway_is_tried_again_quietly() {
engine.send(Command::ObserveGateway {
session: 3,
urls: vec![format!("ws://127.0.0.1:{port}/v1")],
identity: Box::new(tsclientlib::Identity::create()),
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
});
// The first attempts fail (the next ones about 1 s, then 2 s later):
// still connecting, and the user is told nothing.
@@ -811,7 +816,16 @@ async fn not_found_proxy() -> String {
#[tokio::test(flavor = "multi_thread")]
async fn the_next_published_gateway_is_used_when_one_fails() {
let proxy = not_found_proxy().await;
let closed = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
// A port that is taken and never listened on: connecting is refused at once,
// and no other test of this process can be given it meanwhile (one that was
// only free for a moment could be, the listeners of the others bind port 0).
let reserved = tokio::net::TcpSocket::new_v4().unwrap();
reserved.bind("127.0.0.1:0".parse().unwrap()).unwrap();
let closed = reserved.local_addr().unwrap().port();
assert!(
tokio::net::TcpStream::connect(("127.0.0.1", closed)).await.is_err(),
"something listens on port {closed}"
);
let gw = FakeGateway::start().await;
let path = temp_db("fallback");
let engine = Engine::start_with(Settings::in_memory(), History::open(&path).unwrap());
@@ -819,7 +833,7 @@ async fn the_next_published_gateway_is_used_when_one_fails() {
engine.send(Command::ObserveGateway {
session: 4,
urls: vec![proxy, format!("ws://127.0.0.1:{closed}/v1"), gw.url.clone()],
identity: Box::new(tsclientlib::Identity::create()),
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
});
// Within one round: sooner than the shortest wait after a failed round
// (1 s, less 30 %).
@@ -904,7 +918,7 @@ async fn a_login_the_gateway_cannot_do_yet_is_tried_again() {
engine.send(Command::ObserveGateway {
session,
urls: vec![gw.url.clone()],
identity: Box::new(tsclientlib::Identity::create()),
identity: Box::new(to_blob(&tsclientlib::Identity::create())),
});
// After the first wait: about 1 s.
quietly_until(&mut rx, session, Duration::from_secs(3), "observing", observing(session))
@@ -932,6 +946,45 @@ async fn a_refused_login_ends_observing() {
assert_eq!(gw.logins(), 1);
}
/// An identity that cannot be read will not be better tomorrow: like a refused
/// login, observing ends, and the gateway is not even asked.
#[tokio::test(flavor = "multi_thread")]
async fn an_identity_that_cannot_be_read_ends_observing_without_a_login() {
let gw = FakeGateway::start().await;
let engine = Engine::start();
let mut rx = engine.subscribe();
let not_an_identity = voelin_core::IdentityBlob::teamspeak("x", 0, "not an identity");
engine.send(Command::ObserveGateway {
session: 10,
urls: vec![gw.url.clone()],
identity: Box::new(not_an_identity),
});
wait(&mut rx, "connecting", |e| match e {
Event::State { session: 10, state } if state.observe == ObserveState::Connecting => {
Some(())
}
_ => None,
})
.await;
wait(&mut rx, "observing off", |e| match e {
Event::State { session: 10, state } if state.observe == ObserveState::Off => Some(()),
_ => None,
})
.await;
tokio::time::sleep(Duration::from_millis(500)).await;
assert_eq!(gw.logins(), 0);
// The public entry refuses it the same way.
let error = voelin_core::gateway::connect(
&gw.url,
&voelin_core::IdentityBlob::new("voelin", "x", 0, "{}"),
)
.await
.err()
.expect("a refusal");
assert_eq!(error.code(), Some(ErrorCode::AuthFailed), "{error}");
assert_eq!(gw.logins(), 0);
}
/// Selecting the server again while its gateway is still connecting does
/// not start it over, and ends the wait for the next attempt.
#[tokio::test(flavor = "multi_thread")]
@@ -944,7 +997,7 @@ async fn asking_again_while_connecting_tries_at_once() {
let ask = || Command::ObserveGateway {
session: 9,
urls: vec![gw.url.clone()],
identity: Box::new(identity.clone()),
identity: Box::new(to_blob(&identity)),
};
engine.send(ask());
// Three logins fail (waits of about 1 and 2 s); the next wait is about 5 s.
-570
View File
@@ -1,570 +0,0 @@
//! The session through an in-memory [`ServerLink`]: a `FakeLink` hands each
//! connection the test asks for to the test, which plays the server by
//! sending scripted [`LinkEvent`]s and reads the [`LinkCmd`]s the session
//! gives. Presence, chat, the dedup of a message that comes twice, history
//! and the end of a connection are the session's own behaviour; nothing here
//! needs a TeamSpeak server or a TeamSpeak type.
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::{broadcast, mpsc};
use voelin_core::history::MessageSource;
use voelin_core::link::{ConnectOptions, LinkCmd, LinkCtx, LinkEvent, ServerLink};
use voelin_core::settings::Settings;
use voelin_core::stream::{StreamCmd, StreamSetup};
use voelin_core::{
BackendInfo, Command, Engine, Event, History, HistoryMessage, HistorySource, SessionId,
SessionState, Source, VoiceOptions, VoiceState,
};
use voelin_model::{
Capabilities, ChannelId, ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence,
};
/// A connection the session asked the link for.
struct Conn {
options: ConnectOptions,
session: SessionId,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
}
impl Conn {
/// Play `script`, the server's side, in order.
fn play(&self, script: impl IntoIterator<Item = LinkEvent>) {
for event in script {
self.events.send(event).expect("the session listens");
}
}
/// The next command the session gave.
async fn cmd(&mut self) -> LinkCmd {
tokio::time::timeout(Duration::from_secs(10), self.cmds.recv())
.await
.expect("a command in time")
.expect("the session keeps the connection")
}
}
/// Hands every connection to the test.
struct FakeLink {
conns: mpsc::UnboundedSender<Conn>,
}
impl FakeLink {
fn new() -> (Self, mpsc::UnboundedReceiver<Conn>) {
let (conns, rx) = mpsc::unbounded_channel();
(Self { conns }, rx)
}
}
impl ServerLink for FakeLink {
fn spawn(
&self,
options: ConnectOptions,
ctx: LinkCtx,
cmds: mpsc::UnboundedReceiver<LinkCmd>,
events: mpsc::UnboundedSender<LinkEvent>,
) {
let conn = Conn { options, session: ctx.session(), cmds, events };
let _ = self.conns.send(conn);
}
}
const SESSION: SessionId = 1;
const SERVER_UID: &str = "fake-server=";
const ME: u16 = 7;
const ME_UID: &str = "me=";
const LOBBY: ChannelId = 1;
const GAMES: ChannelId = 2;
struct Harness {
engine: Engine,
events: broadcast::Receiver<Event>,
conns: mpsc::UnboundedReceiver<Conn>,
}
impl Harness {
fn start() -> Self {
let (link, conns) = FakeLink::new();
let engine =
Engine::start_with_link(Settings::in_memory(), History::in_memory(), Arc::new(link));
let events = engine.subscribe();
Self { engine, events, conns }
}
/// Ask for a voice connection and take it from the link.
async fn connect(&mut self) -> Conn {
let options = VoiceOptions::new("fake.test:9987", "tester");
self.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
tokio::time::timeout(Duration::from_secs(10), self.conns.recv())
.await
.expect("the session spawns the link")
.expect("the link lives")
}
/// The next event `f` picks, skipping the others.
async fn next<T>(&mut self, mut f: impl FnMut(Event) -> Option<T>) -> T {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
if let Some(t) = f(self.events.recv().await.expect("engine events")) {
return t;
}
}
})
.await
.expect("event in time")
}
/// The next state of the session that `ok` accepts.
async fn state(&mut self, mut ok: impl FnMut(&SessionState) -> bool) -> SessionState {
self.next(|e| match e {
Event::State { state, .. } if ok(&state) => Some(state),
_ => None,
})
.await
}
/// The next live chat message.
async fn chat(&mut self) -> ChatMessage {
self.next(|e| match e {
Event::Chat { message, .. } => Some(message),
_ => None,
})
.await
}
/// The messages stored for `target`, oldest first.
async fn stored(&self, target: ChatTarget) -> Vec<HistoryMessage> {
self.engine
.history()
.page(SERVER_UID, &target, Default::default(), false)
.await
.expect("the history")
}
}
fn now_ms() -> i64 {
SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64
}
fn capabilities(streams: bool) -> Capabilities {
Capabilities { streams, file_transfer: true, ..Default::default() }
}
fn backend() -> BackendInfo {
BackendInfo { product: "Fake".into(), version: "1.2".into() }
}
fn connected(streams: bool) -> LinkEvent {
LinkEvent::Connected {
name: "Fake Server".into(),
backend: backend(),
capabilities: capabilities(streams),
own_client: ME,
server_uid: SERVER_UID.into(),
own_uid: Some(ME_UID.into()),
}
}
fn client(id: u16, nickname: &str, channel: ChannelId) -> ClientInfo {
ClientInfo {
id,
uid: Some(format!("{nickname}=")),
nickname: nickname.into(),
channel,
..Default::default()
}
}
/// Two channels, three clients; we are in the second channel.
fn presence() -> Presence {
let channel = |id, name: &str| ChannelInfo { id, name: name.into(), ..Default::default() };
let mut presence = Presence { server_name: "Fake Server".into(), ..Default::default() };
presence.channels.insert(LOBBY, channel(LOBBY, "Lobby"));
presence.channels.insert(GAMES, channel(GAMES, "Games"));
for c in [client(ME, "tester", GAMES), client(8, "alice", GAMES), client(9, "bob", LOBBY)] {
presence.clients.insert(c.id, c);
}
presence
}
fn message(author: &str, text: &str, ts_ms: i64) -> ChatMessage {
ChatMessage {
target: ChatTarget::Channel(GAMES),
author_name: author.into(),
author_uid: Some(format!("{author}=")),
author_id: None,
text: text.into(),
ts_ms,
via_relay: false,
blocked: false,
}
}
/// Connecting, the server's presence, moving, talking, a failing command
/// and the end of the connection, as the session reports them.
#[tokio::test(flavor = "multi_thread")]
async fn presence_follows_the_link_until_it_disconnects() {
let mut h = Harness::start();
let conn = h.connect().await;
// What the link was given.
assert_eq!(
(conn.options.address.as_str(), conn.options.nickname.as_str()),
("fake.test:9987", "tester")
);
assert_eq!(conn.session, SESSION);
h.state(|s| s.voice == VoiceState::Connecting).await;
conn.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
// In the order the session tells them: the server, its presence, our channel.
let (name, info, caps) = h
.next(|e| match e {
Event::ServerInfo { name, backend, capabilities, .. } => {
Some((name, backend, capabilities))
}
_ => None,
})
.await;
assert_eq!((name.as_str(), info.label().as_str()), ("Fake Server", "Fake 1.2"));
assert_eq!(caps, capabilities(false));
let shown = h
.next(|e| match e {
Event::Presence { presence, .. } if !presence.clients.is_empty() => Some(presence),
_ => None,
})
.await;
assert_eq!(*shown, presence());
let state = h.state(|s| s.own_channel == Some(GAMES)).await;
assert_eq!(state.voice, VoiceState::Connected);
assert_eq!(state.own_client, Some(ME));
assert_eq!(state.server_uid.as_deref(), Some(SERVER_UID));
assert_eq!(state.presence_source, Some(Source::Voice));
conn.play([
LinkEvent::Talking { client: 8, talking: true },
LinkEvent::Poke {
from: 8,
from_uid: Some("alice=".into()),
from_name: "alice".into(),
message: "wake up".into(),
},
LinkEvent::Error("move refused".into()),
]);
h.next(|e| matches!(e, Event::Talking { client: 8, talking: true, .. }).then_some(())).await;
let poke = h
.next(|e| match e {
Event::Poke { from_name, message, blocked, .. } => Some((from_name, message, blocked)),
_ => None,
})
.await;
assert_eq!(poke, ("alice".into(), "wake up".into(), false));
let error = h
.next(|e| match e {
Event::Error { message, .. } => Some(message),
_ => None,
})
.await;
assert_eq!(error, "move refused");
// The link ends the connection: the session forgets what it showed.
conn.play([LinkEvent::Disconnected(Some("server shut down".into()))]);
let state = h.state(|s| s.voice == VoiceState::Disconnected).await;
assert_eq!((state.own_channel, state.own_client), (None, None));
let error = h
.next(|e| match e {
Event::Error { message, .. } => Some(message),
_ => None,
})
.await;
assert_eq!(error, "voice: server shut down");
let state = h.state(|s| s.presence_source.is_none()).await;
assert_eq!(state.voice, VoiceState::Disconnected);
let shown = h
.next(|e| match e {
Event::Presence { presence, .. } => Some(presence),
_ => None,
})
.await;
assert!(shown.clients.is_empty() && shown.channels.is_empty());
}
/// What the user asks for reaches the link; streams only where the link's
/// capabilities say it has them.
#[tokio::test(flavor = "multi_thread")]
async fn commands_reach_the_link() {
let mut h = Harness::start();
let mut conn = h.connect().await;
conn.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
let engine = h.engine.clone();
engine.send(Command::SendChat {
session: SESSION,
target: ChatTarget::Channel(GAMES),
text: "hello".into(),
});
let LinkCmd::SendChat(target, text) = conn.cmd().await else { panic!("a chat message") };
assert_eq!((target, text.as_str()), (ChatTarget::Channel(GAMES), "hello"));
engine.send(Command::MoveToChannel {
session: SESSION,
channel: LOBBY,
password: Some("pw".into()),
});
let LinkCmd::Move(channel, password) = conn.cmd().await else { panic!("a move") };
assert_eq!((channel, password.as_deref()), (LOBBY, Some("pw")));
engine.send(Command::SetInputMuted { session: SESSION, muted: true });
assert!(matches!(conn.cmd().await, LinkCmd::SetInputMuted(true)));
assert!(h.state(|s| s.input_muted).await.input_muted);
engine.send(Command::Poke { session: SESSION, client: 8, message: "hi".into() });
assert!(matches!(conn.cmd().await, LinkCmd::Poke { client: 8, .. }));
engine.send(Command::ListFiles {
session: SESSION,
request: 5,
channel: GAMES,
password: None,
path: "/docs/".into(),
});
let LinkCmd::ListFiles { request, dir } = conn.cmd().await else { panic!("a file list") };
assert_eq!((request, dir.channel, dir.path.as_str()), (5, GAMES, "/docs/"));
// No streams in the capabilities: the session refuses them itself.
let setup = || StreamSetup { name: "screen".into(), ..Default::default() };
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
let error = h
.next(|e| match e {
Event::Error { message, .. } => Some(message),
_ => None,
})
.await;
assert!(error.contains("streams"), "{error}");
assert!(conn.cmds.try_recv().is_err(), "nothing reached the link");
// A link with streams: stream commands go to it, and end with the connection.
let mut with_streams = {
let link_engine = h.engine.clone();
link_engine.send(Command::ConnectVoice {
session: SESSION,
options: Box::new(VoiceOptions::new("fake.test:9987", "tester")),
});
h.conns.recv().await.expect("the second connection")
};
// The replaced connection is told to go.
assert!(matches!(conn.cmd().await, LinkCmd::Disconnect));
with_streams.play([connected(true)]);
h.next(|e| match e {
Event::ServerInfo { capabilities, .. } if capabilities.streams => Some(()),
_ => None,
})
.await;
// A connection with streams is given the (empty) stream directory first.
let LinkCmd::Stream(StreamCmd::Directory(directory)) = with_streams.cmd().await else {
panic!("the stream directory")
};
assert!(directory.is_empty());
engine.send(Command::StartStream { session: SESSION, setup: setup(), auto_accept: true });
let LinkCmd::Stream(StreamCmd::Start { setup, auto_accept }) = with_streams.cmd().await else {
panic!("a stream start")
};
assert_eq!((setup.name.as_str(), auto_accept), ("screen", true));
engine.send(Command::StopStream { session: SESSION });
assert!(matches!(with_streams.cmd().await, LinkCmd::Stream(StreamCmd::Stop)));
engine.send(Command::DisconnectVoice { session: SESSION });
assert!(matches!(with_streams.cmd().await, LinkCmd::Disconnect));
}
/// A reconnect ends the streams of the connection it replaces through that
/// connection, before the connection itself: the old link is given
/// `StreamCmd::Shutdown` and only then `Disconnect`. A link that ends its
/// connection on `Disconnect` (the TeamSpeak one stops reading commands
/// there) relies on this order for the streams to hear of their end.
#[tokio::test(flavor = "multi_thread")]
async fn a_reconnect_shuts_the_streams_down_before_the_old_connection() {
let mut h = Harness::start();
let mut old = h.connect().await;
old.play([
connected(true),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
let LinkCmd::Stream(StreamCmd::Directory(directory)) = old.cmd().await else {
panic!("the stream directory")
};
assert!(directory.is_empty());
// Connecting again replaces the connection.
let _new = h.connect().await;
let LinkCmd::Stream(StreamCmd::Shutdown(reason)) = old.cmd().await else {
panic!("the streams end first")
};
assert_eq!(reason, "voice reconnecting");
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
}
/// A message we send is stored at once; the server's copy of it merges
/// into the same row, and is shown (once).
#[tokio::test(flavor = "multi_thread")]
async fn a_sent_message_and_its_echo_are_one_message() {
let mut h = Harness::start();
let mut conn = h.connect().await;
conn.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
h.engine.send(Command::SendChat {
session: SESSION,
target: ChatTarget::Channel(GAMES),
text: "hello".into(),
});
assert!(matches!(conn.cmd().await, LinkCmd::SendChat(..)));
// The server sends it back to everyone in the channel, to us too.
let mut echo = message("tester", "hello", now_ms());
echo.author_uid = Some(ME_UID.into());
echo.author_id = Some(ME);
conn.play([LinkEvent::Chat(echo.clone())]);
let shown = h.chat().await;
assert_eq!((shown.author_name.as_str(), shown.text.as_str()), ("tester", "hello"));
// A marker: what comes next is the next message, not a second "hello".
conn.play([LinkEvent::Chat(message("alice", "marker", now_ms()))]);
assert_eq!(h.chat().await.text, "marker");
let rows = h.stored(ChatTarget::Channel(GAMES)).await;
let texts: Vec<_> = rows.iter().map(|m| m.message.text.as_str()).collect();
assert_eq!(texts, ["hello", "marker"]);
assert_eq!(rows[0].source, MessageSource::Local);
}
/// A message that comes twice (the server's and a relay's copy, with the
/// relay's `[nick] ` prefix) is shown once.
#[tokio::test(flavor = "multi_thread")]
async fn a_message_that_comes_twice_is_shown_once() {
let mut h = Harness::start();
let conn = h.connect().await;
h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) });
conn.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
let t = now_ms();
let mut relayed = message("alice", "[alice] gg everyone", t + 300);
relayed.via_relay = true;
conn.play([
LinkEvent::Chat(message("alice", "gg everyone", t)),
LinkEvent::Chat(relayed),
// The same words much later are another message.
LinkEvent::Chat(message("alice", "gg everyone", t + 10_000)),
LinkEvent::Chat(message("bob", "gg everyone", t + 10_100)),
]);
let shown: Vec<_> = {
let mut shown = Vec::new();
while shown.len() < 3 {
shown.push(h.chat().await);
}
shown
};
let who: Vec<_> = shown.iter().map(|m| (m.author_name.as_str(), m.ts_ms)).collect();
assert_eq!(who, [("alice", t), ("alice", t + 10_000), ("bob", t + 10_100)]);
}
/// Stored messages come back when a chat opens, also after the connection
/// is gone; the server's id keys them.
#[tokio::test(flavor = "multi_thread")]
async fn history_is_kept_across_the_connection() {
let mut h = Harness::start();
let conn = h.connect().await;
conn.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
let t = now_ms();
conn.play([
LinkEvent::Chat(message("alice", "first", t)),
LinkEvent::Chat(message("bob", "second", t + 1_000)),
// A private message to us is stored under its peer, not the channel.
LinkEvent::Chat(ChatMessage {
target: ChatTarget::Private("alice=".into()),
..message("alice", "psst", t + 2_000)
}),
]);
for _ in 0..3 {
h.chat().await;
}
conn.play([LinkEvent::Disconnected(None)]);
h.state(|s| s.voice == VoiceState::Disconnected).await;
h.engine.send(Command::OpenChat { session: SESSION, target: ChatTarget::Channel(GAMES) });
// The stored page (the live batches of the messages came before).
let messages = h
.next(|e| match e {
Event::ChatHistory { messages, source: HistorySource::Local, .. } => Some(messages),
_ => None,
})
.await;
let texts: Vec<_> = messages.iter().map(|m| m.message.text.as_str()).collect();
assert_eq!(texts, ["first", "second"]);
let private = h.stored(ChatTarget::Private("alice=".into())).await;
assert_eq!(private.len(), 1);
assert_eq!(private[0].message.text, "psst");
}
/// Events of a connection the session replaced do not reach it.
#[tokio::test(flavor = "multi_thread")]
async fn a_replaced_connection_is_ignored() {
let mut h = Harness::start();
let mut old = h.connect().await;
old.play([
connected(false),
LinkEvent::Presence(Box::new(presence())),
LinkEvent::OwnChannel(GAMES),
]);
h.state(|s| s.own_channel == Some(GAMES)).await;
let new = h.connect().await;
assert!(matches!(old.cmd().await, LinkCmd::Disconnect));
// The old connection winds down, and says more than it should.
let mut stale = presence();
stale.clients.insert(10, client(10, "ghost", LOBBY));
old.play([
LinkEvent::Presence(Box::new(stale)),
LinkEvent::Chat(message("ghost", "boo", now_ms())),
LinkEvent::Disconnected(None),
]);
let mut fresh = presence();
fresh.clients.remove(&9);
new.play([
connected(false),
LinkEvent::Presence(Box::new(fresh.clone())),
LinkEvent::OwnChannel(LOBBY),
]);
// Only the new connection's presence is shown (nobody else has 2 clients).
let shown = h
.next(|e| match e {
Event::Presence { presence, .. } if presence.clients.len() == fresh.clients.len() => {
Some(presence)
}
_ => None,
})
.await;
assert_eq!(*shown, fresh);
let state = h.state(|s| s.own_channel == Some(LOBBY)).await;
assert_eq!(state.voice, VoiceState::Connected, "the old disconnect did not count");
new.play([LinkEvent::Chat(message("alice", "hello", now_ms()))]);
assert_eq!(h.chat().await.text, "hello", "the old connection's chat never showed");
}
+40 -2
View File
@@ -1,17 +1,33 @@
//! Engine against the development servers (dev/docker-compose.yml).
//! Runs only with `VOELIN_LIVE=1`; `scripts/it-smoke.sh` sets it.
use std::sync::LazyLock;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio::sync::broadcast::Receiver;
use tokio::time::{Instant, timeout_at};
use voelin_core::{Command, Engine, Event, ObserveState, Source, VoiceOptions, VoiceState};
use voelin_core::{
Command, Engine, Event, ObserveState, QueryLogin, QueryTransport, Source, VoiceOptions,
VoiceState,
};
use voelin_model::ChatTarget;
fn live() -> bool {
std::env::var("VOELIN_LIVE").is_ok_and(|v| v == "1")
}
/// The TeamSpeak 6 server's banners are the server's, and `ts6_banners` sets and
/// unsets them there. While it does, whatever else connects to the server is
/// told the addresses of those banners, and an engine fetches what it is told
/// (as it should): the requests of such an engine reached the HTTP server of
/// `ts6_banners`, which counts the requests of the engine under test, and the
/// test failed on `disabled policy must prevent HTTP requests` in every run
/// that had the tests of this file run side by side (as they do). The tests
/// that connect to the server hold this shared, `ts6_banners` exclusively: it
/// runs with the server to itself, and the others before or after it.
static TS6: LazyLock<RwLock<()>> = LazyLock::new(|| RwLock::new(()));
/// Wait for an event matching `f`, failing after 20 s.
async fn wait_for(
rx: &mut Receiver<Event>,
@@ -45,7 +61,7 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
.await;
// Session 2: invisible, through own query credentials.
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(query) });
engine.send(Command::ObserveQuery { session: 2, connect: Box::new(login(&query)) });
let (mut observing, mut sees_voice_client) = (false, false);
wait_for(&mut events, "query presence with the voice client", |e| {
match e {
@@ -93,6 +109,24 @@ async fn engine_roundtrip(voice_addr: &str, query: voelin_query::Connect) {
tokio::time::sleep(Duration::from_millis(500)).await;
}
/// The credentials of a query connection, as the engine takes them.
fn login(connect: &voelin_query::Connect) -> QueryLogin {
QueryLogin {
transport: match connect.transport {
voelin_query::Transport::Raw => QueryTransport::Raw,
voelin_query::Transport::Ssh => QueryTransport::Ssh,
voelin_query::Transport::Http => QueryTransport::Http,
},
address: connect.addr.clone(),
user: connect.user.clone(),
secret: connect.secret.clone(),
server_port: connect.server_port,
server_id: connect.server_id,
// The development servers allowlist their clients.
allowlisted: connect.line.rate_limit.is_none(),
}
}
fn query(transport: voelin_query::Transport, addr: &str) -> voelin_query::Connect {
voelin_query::Connect {
transport,
@@ -110,6 +144,7 @@ async fn ts6_engine() {
if !live() {
return;
}
let _server = TS6.read().await;
engine_roundtrip("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022"))
.await;
}
@@ -237,6 +272,7 @@ async fn ts6_channel_joins() {
if !live() {
return;
}
let _server = TS6.read().await;
channel_joins("127.0.0.1:9988", query(voelin_query::Transport::Ssh, "127.0.0.1:10022")).await;
}
@@ -308,6 +344,7 @@ async fn ts6_banners() {
if !live() {
return;
}
let _server = TS6.write().await;
let voice_addr =
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
let query_addr =
@@ -491,6 +528,7 @@ async fn ts6_avatars() {
if !live() {
return;
}
let _server = TS6.read().await;
let voice_addr =
std::env::var("VOELIN_BANNER_VOICE_ADDR").unwrap_or_else(|_| "127.0.0.1:9988".into());
let dir = std::env::temp_dir().join(format!("voelin-live-avatars-{}", std::process::id()));
@@ -0,0 +1,124 @@
//! The engine on a `voelin_proto::link::Session` that no TeamSpeak code
//! made: `Engine::start_with_backends` takes the connector registry, and the
//! scheme of a session's address picks the connector. The fake host of the
//! protocol repository stands for a Voelin host here (the fuller tests of the
//! seam on the fake host come with the next slice of
//! `docs/session-seam.md`).
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::broadcast;
use voelin_core::settings::Settings;
use voelin_core::{
Backends, Command, Engine, Event, History, SessionState, VoiceOptions, VoiceState,
};
use voelin_proto::test_util::FakeConnector;
use voelin_proto::v1::{self, entity::Kind};
const SESSION: u64 = 1;
async fn next<T>(
events: &mut broadcast::Receiver<Event>,
mut f: impl FnMut(Event) -> Option<T>,
) -> T {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
if let Some(t) = f(events.recv().await.expect("engine events")) {
return t;
}
}
})
.await
.expect("an event in time")
}
fn host_with_two_channels(connector: &FakeConnector) {
let host = connector.host();
let put = |kind: Kind| host.put(v1::Entity { kind: Some(kind) }).unwrap();
put(Kind::Server(v1::Server {
id: 1,
name: "Fake Host".into(),
uid: "fake-host".into(),
default_channel_id: 10,
..Default::default()
}));
for (id, name, position) in [(10, "Lobby", 0), (11, "Games", 1024)] {
put(Kind::Channel(v1::Channel {
id,
server_id: 1,
kind: v1::ChannelKind::Voice as i32,
name: name.into(),
position,
..Default::default()
}));
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_session_of_a_registered_connector_is_the_engines_voice_source() {
let connector = FakeConnector::new();
host_with_two_channels(&connector);
let mut backends = Backends::empty();
backends.register(Arc::new(connector.clone()));
let engine = Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
let mut events = engine.subscribe();
engine.send(Command::ConnectVoice {
session: SESSION,
options: Box::new(VoiceOptions::new("fake://host", "tester")),
});
let (name, backend) = next(&mut events, |e| match e {
Event::ServerInfo { name, backend, .. } => Some((name, backend)),
_ => None,
})
.await;
assert_eq!((name.as_str(), backend.product.as_str()), ("Fake Host", "voelin-fake"));
let presence = next(&mut events, |e| match e {
Event::Presence { presence, .. } if !presence.channels.is_empty() => Some(presence),
_ => None,
})
.await;
let channels: Vec<_> =
presence.channels.values().map(|c| (c.id, c.name.as_str(), c.order)).collect();
assert_eq!(channels, [(10, "Lobby", 0), (11, "Games", 10)]);
// The host was asked once, with the nickname and the TeamSpeak-shaped
// credential the engine makes of its options for now.
let connects = connector.connects();
assert_eq!(connects.len(), 1);
assert_eq!(connects[0].address, "fake://host");
assert_eq!(connects[0].hello.nickname, "tester");
// A move is a request to the host; the host's voice state is where we are.
engine.send(Command::MoveToChannel { session: SESSION, channel: 11, password: None });
let state: SessionState = next(&mut events, |e| match e {
Event::State { state, .. } if state.own_channel == Some(11) => Some(state),
_ => None,
})
.await;
assert_eq!(state.voice, VoiceState::Connected);
engine.send(Command::DisconnectVoice { session: SESSION });
next(&mut events, |e| match e {
Event::State { state, .. } if state.voice == VoiceState::Disconnected => Some(()),
_ => None,
})
.await;
}
#[tokio::test(flavor = "multi_thread")]
async fn an_address_no_connector_serves_fails_with_the_registry_s_words() {
let engine =
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), Backends::empty());
let mut events = engine.subscribe();
engine.send(Command::ConnectVoice {
session: SESSION,
options: Box::new(VoiceOptions::new("voelin://host/i/code", "tester")),
});
let error = next(&mut events, |e| match e {
Event::Error { message, .. } => Some(message),
_ => None,
})
.await;
assert_eq!(error, "voice: no connector for voelin://host/i/code");
}
File diff suppressed because it is too large. Load diff
@@ -10,6 +10,10 @@ use voelin_core::settings::Settings;
use voelin_core::{Command, Contact, DownloadTo, Engine, Event, History, Relation, TransferState};
use voelin_model::FileRef;
mod common;
use common::closed;
async fn next<T>(rx: &mut broadcast::Receiver<Event>, mut f: impl FnMut(Event) -> Option<T>) -> T {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
@@ -165,6 +169,7 @@ async fn contacts_are_kept_in_the_database() {
engine.history().flush();
}
// A new engine attaches the database later: the contacts come back.
closed(&path).await;
let engine = Engine::start();
let mut rx = engine.subscribe();
engine.send(Command::AttachHistory(History::open(&path).unwrap()));
+1 -1
View File
@@ -24,7 +24,7 @@ tokio = { version = "1", features = ["macros", "net", "rt", "sync"], optional =
# TLS (`wss://`, as gateways run behind a proxy) with the system's
# certificates; rustls and its crates are in the tree already (reqwest).
tokio-tungstenite = { version = "0.30", optional = true, features = ["rustls-tls-native-roots"] }
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
tsproto-types = { path = "../proto/tsproto-types" }
[lints]
+1 -1
View File
@@ -29,7 +29,7 @@ toml = "1.1.6"
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
voelin-observer = { path = "../voelin-observer" }
voelin-query = { path = "../voelin-query" }
+1 -1
View File
@@ -9,7 +9,7 @@
# -e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw
# Logs: docker logs -f tsgw (more: -e TSGW_LOG_LEVEL=debug; also to a file in
# the volume: -e TSGW_LOG_FILE=logs/tsgw.log). See docs/gateway-admin.md.
FROM rust:1.94-bookworm AS build
FROM rust:1.95-bookworm AS build
WORKDIR /src
RUN apt-get update && apt-get install -y --no-install-recommends cmake git libasound2-dev openssh-client && rm -rf /var/lib/apt/lists/*
# voelin-identity comes from the private VoelinProtocol repository, fetched
+53
View File
@@ -0,0 +1,53 @@
[package]
name = "voelin-gpui"
version = "0.0.1-alpha"
description = "The GPUI front end of the desktop app, under construction: it runs on the same engine as the Slint front end (voelin-ui) until it reaches parity."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[lib]
name = "voelin_gpui"
path = "src/lib.rs"
[[bin]]
name = "voelin-gpui"
path = "src/main.rs"
[dependencies]
anyhow = "1.0.104"
# GPUI, gpui-component and gpui-kit-assets behind one pinned dependency.
gpui-kit = { workspace = true }
# The engine's runtime and the channel of its events (a tokio receiver needs no
# reactor, so GPUI's executor can await it).
tokio = { version = "1.53.1", features = ["rt-multi-thread", "sync", "time"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
# The engine, with the desktop's capture and codecs: ashpd on async-io (the
# commit that moved voelin-media and voelin-platform to it) lets this binary
# hold both the portals and gpui-kit.
voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device", "media-desktop"] }
# The app's name and id, the hotkeys and portals of the slices to come.
voelin-platform = { path = "../voelin-platform" }
# The Host trait's types (what the store knows of a chat's read marker).
voelin-store = { path = "../voelin-store" }
# The view models and the state, shared with the Slint front end.
voelin-ui-vm = { path = "../voelin-ui-vm" }
# The meter reads /proc/self (CPU ticks per second, the page size).
[target.'cfg(target_os = "linux")'.dependencies]
rustix = { version = "1.1.5", features = ["param"] }
[dev-dependencies]
# GPUI's test platform (`#[gpui::test]`, `TestAppContext`): the front end's tests
# need no display. gpui-kit's own `test-support` feature is not used: it names
# the optional `gpui-fast` backend in weak features, which puts gpui-fast and
# its tree into Cargo.lock and pins taffy to 0.15.0 for every build. gpui-kit
# pins `gpui-pre` exactly, so this line moves with its `=` pin (a mismatch does
# not resolve).
gpui = { package = "gpui-pre", version = "=0.3.10", features = ["test-support"] }
[lints]
workspace = true
+34
View File
@@ -0,0 +1,34 @@
//! Embeds the client's Lucide icons: `crates/voelin-ui/ui/assets/icons/*.svg`
//! (Lucide 1.48, the set the Slint front end draws) become a sorted table of
//! `include_bytes!` in `$OUT_DIR/icons.rs`, which `assets.rs` serves as
//! gpui-component's `icons/<name>.svg` paths before gpui-kit-assets' own
//! (Lucide 1.43) catalogue. No dependency: the directory is read and the
//! table written with `std`.
use std::fmt::Write as _;
use std::path::PathBuf;
fn main() {
let manifest =
PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR"));
let dir = manifest.join("../voelin-ui/ui/assets/icons");
println!("cargo:rerun-if-changed={}", dir.display());
let mut names: Vec<String> = std::fs::read_dir(&dir)
.unwrap_or_else(|e| panic!("the client's icons are at {}: {e}", dir.display()))
.filter_map(|entry| entry.ok()?.file_name().into_string().ok())
.filter(|name| name.ends_with(".svg"))
.collect();
names.sort();
assert!(!names.is_empty(), "no icons in {}", dir.display());
let mut table = String::from(
"/// The client's icons by file name, sorted.\npub static ICONS: &[(&str, &[u8])] = &[\n",
);
for name in &names {
let path = dir.join(name);
let path = path.canonicalize().unwrap_or(path);
let _ = writeln!(table, "\t({name:?}, include_bytes!({:?})),", path.display().to_string());
}
table.push_str("];\n");
let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("OUT_DIR")).join("icons.rs");
std::fs::write(out, table).expect("write icons.rs");
}
+453
View File
@@ -0,0 +1,453 @@
//! The root state of the window, `Entity<AppState>`: everything the client
//! knows (the toolkit-free [`voelin_ui_vm`] state and the friends and pokes
//! beside it) and the three loops that keep it current on GPUI's thread:
//!
//! - the **engine's events**: a foreground task awaits the receiver of
//! [`crate::engine::HostedEngine`] (a tokio channel needs no reactor, so
//! GPUI's executor can poll it), hands every event to
//! [`events::handle`] and tells the entity to redraw (`cx.notify()`), the
//! pattern of spike 3's hotkey task;
//! - the **tick**, once a second, a loop of `background_executor().timer`
//! (the Slint front end's `slint::Timer` calling `App::tick`);
//! - **later**: other threads (a hotkey, a camera, a decoder) cannot touch the
//! entity, and GPUI's `AsyncApp` is not `Send`, so they hold a [`Later`], a
//! channel of jobs a third foreground task runs on GPUI's thread, as
//! `later(|app| ...)` does in the Slint front end.
//!
//! What a transition asks for besides the state (`Update`: which parts to
//! draw again, what to keep, the streams' capture and decoder) belongs to
//! the slices that have those parts; today only the engine commands go out
//! and the warnings are logged.
use std::time::{Duration, Instant};
use gpui_kit::Context;
use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender};
use voelin_core::{AudioSettings, Command, Engine, Event, VoiceState};
use voelin_store::{ChatRead, ChatTarget as StoredTarget};
use voelin_ui_vm::bridge::ChatLine;
use voelin_ui_vm::events;
use voelin_ui_vm::host::{Host, Update};
use voelin_ui_vm::settings::UiSettings;
use voelin_ui_vm::social::logic::Social;
use crate::meter::Counters;
/// The toolkit-free state of the client, with the chat lines of a tab as plain
/// rows (what a front end that draws again from the list needs).
pub type VmState = voelin_ui_vm::state::AppState<Vec<ChatLine>>;
/// A job for GPUI's thread, from any thread.
type Job = Box<dyn FnOnce(&mut AppState, &mut Context<AppState>) + Send>;
/// How other threads reach the root state: `later.run(|app, cx| ...)` runs
/// the closure on GPUI's thread with the entity (the Slint front end's
/// `later`). Cloneable and `Send`; the closure must be `Send` too.
#[derive(Clone)]
pub struct Later(UnboundedSender<Job>);
impl Later {
/// Run `job` on GPUI's thread soon. `false` once a job has found the
/// window gone (the entity released): the loop that runs the jobs notices
/// that only when a job reaches it, ends and drops the channel, so the
/// first job sent after the window went answers `true` and is never run.
/// `true` is a promise of nothing more than that the job was queued.
pub fn run(
&self,
job: impl FnOnce(&mut AppState, &mut Context<AppState>) + Send + 'static,
) -> bool {
self.0.send(Box::new(job)).is_ok()
}
}
/// What the transitions of the state ask of this front end while they run.
/// There is no store yet (the shell slice opens it): nothing was read, and
/// nothing is kept.
#[derive(Debug, Default)]
struct ShellHost;
impl Host for ShellHost {
fn demo_ui(&self) -> bool {
false
}
fn chat_shown(&self) -> bool {
false
}
fn watching(&self) -> bool {
false
}
fn autowatch(&self) -> bool {
false
}
fn studio_streams_to(&self, _session: i64) -> bool {
false
}
fn preview_limit(&self) -> u64 {
0
}
fn fetch_images(&self) -> bool {
false
}
fn dm_shown(&self, _session: i64, _uid: &str) -> bool {
false
}
fn chat_reads(&self, _server_uid: &str) -> Result<Vec<(StoredTarget, ChatRead)>, String> {
Ok(Vec::new())
}
fn set_chat_read(
&self,
_server_uid: &str,
_target: &StoredTarget,
_read: &ChatRead,
) -> Result<(), String> {
Ok(())
}
}
/// The root entity.
pub struct AppState {
/// What the client knows apart from the window.
pub vm: VmState,
/// The friends, pokes and notices the social screens keep.
pub social: Social<()>,
/// Engine events handled since the window opened.
pub events_handled: u64,
/// One-second ticks since the window opened.
pub ticks: u64,
engine: Option<Engine>,
host: ShellHost,
started: Instant,
counters: Counters,
later: Later,
}
impl AppState {
/// The state at start, with its three loops running: the engine's
/// `events` (the engine is `None` in tests that need none), the tick and
/// the jobs of [`Later`]. They end when the entity is released.
pub fn new(
engine: Option<Engine>,
events: UnboundedReceiver<Event>,
counters: Counters,
cx: &mut Context<Self>,
) -> Self {
let (later, mut jobs) = mpsc::unbounded_channel::<Job>();
cx.spawn(async move |this, cx| {
let mut events = events;
while let Some(event) = events.recv().await {
if this.update(cx, |state, cx| state.handle_event(event, cx)).is_err() {
break;
}
}
})
.detach();
cx.spawn(async move |this, cx| {
loop {
cx.background_executor().timer(Duration::from_secs(1)).await;
if this.update(cx, |state, cx| state.tick(cx)).is_err() {
break;
}
}
})
.detach();
cx.spawn(async move |this, cx| {
while let Some(job) = jobs.recv().await {
if this
.update(cx, |state, cx| {
state.counters.later_jobs.incr();
job(state, cx);
cx.notify();
})
.is_err()
{
break;
}
}
})
.detach();
Self {
vm: VmState::new(
Vec::new(),
UiSettings::default(),
AudioSettings::default(),
Default::default(),
),
social: Social::default(),
events_handled: 0,
ticks: 0,
engine,
host: ShellHost,
started: Instant::now(),
counters,
later: Later(later),
}
}
/// The handle other threads use to run something on GPUI's thread.
pub fn later(&self) -> Later {
self.later.clone()
}
/// What an engine event does to the state ([`events::handle`], the one
/// dispatch of both front ends), and what comes of it for the engine.
pub fn handle_event(&mut self, event: Event, cx: &mut Context<Self>) {
self.events_handled += 1;
self.counters.engine_events.incr();
let update = events::handle(&mut self.vm, &mut self.social, &self.host, event);
self.perform(update);
self.counters.connections.set(self.connections() as u64);
cx.notify();
}
/// Do what an update asks that this front end has the parts for: the
/// engine's commands go out, the warnings are logged.
fn perform(&mut self, update: Update) {
if let Some(engine) = &self.engine {
for command in update.commands {
engine.send(command);
}
}
for warning in update.warnings {
tracing::warn!("{warning}");
}
}
/// The once-a-second work: what the Slint front end's `App::tick` will be
/// here (stream statistics, stored settings); today it counts.
pub fn tick(&mut self, cx: &mut Context<Self>) {
self.ticks += 1;
self.counters.ticks.incr();
cx.notify();
}
/// Voice connections that are up.
pub fn connections(&self) -> usize {
self.vm.sessions.values().filter(|view| view.state.voice == VoiceState::Connected).count()
}
/// Seconds since the window opened.
pub fn uptime(&self) -> Duration {
self.started.elapsed()
}
/// The one line of state the window shows: the version, how many voice
/// connections are up, how many engine events came and how long the
/// window has run. Each part moves by a loop above, so a line that
/// changes shows that the loop runs.
pub fn state_line(&self) -> String {
let connections = self.connections();
format!(
"{} {} · {} connection{} · {} engine event{} · {} s up",
voelin_platform::APP_NAME,
env!("CARGO_PKG_VERSION"),
connections,
if connections == 1 { "" } else { "s" },
self.events_handled,
if self.events_handled == 1 { "" } else { "s" },
self.ticks,
)
}
/// Leave the servers properly, so no ghost client stays behind until it
/// times out (the window is closing): tell the engine to close every
/// session. Returns how many it told, so that the caller can give the
/// engine time to act on them before the runtime goes (none without an
/// engine).
pub fn shutdown(&self) -> usize {
let Some(engine) = &self.engine else { return 0 };
for id in self.vm.sessions.keys() {
engine.send(Command::CloseSession { session: *id as u64 });
}
self.vm.sessions.len()
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use gpui::TestAppContext;
use gpui_kit::AppContext as _;
use voelin_core::{Command, Event, SessionState, VoiceState};
use super::*;
use crate::engine::HostedEngine;
fn voice(voice: VoiceState) -> Event {
Event::State { session: 1, state: SessionState { voice, ..Default::default() } }
}
/// The entity of a test with no engine behind it: `tx` stands in for the
/// engine's events.
fn entity(
cx: &mut TestAppContext,
) -> (gpui_kit::Entity<AppState>, UnboundedSender<Event>, Counters) {
let (tx, rx) = mpsc::unbounded_channel();
let counters = Counters::default();
let app = cx.new({
let counters = counters.clone();
move |cx| AppState::new(None, rx, counters, cx)
});
(app, tx, counters)
}
#[gpui::test]
fn an_injected_engine_event_reaches_the_entity(cx: &mut TestAppContext) {
let (app, tx, counters) = entity(cx);
app.read_with(cx, |app, _| {
assert_eq!(app.connections(), 0);
assert!(app.state_line().contains("0 connections · 0 engine events"));
});
tx.send(voice(VoiceState::Connected)).unwrap();
cx.run_until_parked();
app.read_with(cx, |app, _| {
assert_eq!(app.events_handled, 1);
assert_eq!(app.connections(), 1);
assert_eq!(app.vm.status, "Connected", "the transition's status line");
assert!(
app.state_line().contains("1 connection · 1 engine event"),
"{}",
app.state_line()
);
});
assert_eq!(counters.engine_events.get(), 1);
assert_eq!(counters.connections.get(), 1);
tx.send(voice(VoiceState::Disconnected)).unwrap();
cx.run_until_parked();
app.read_with(cx, |app, _| {
assert_eq!((app.events_handled, app.connections()), (2, 0));
});
}
#[gpui::test]
fn the_entity_redraws_on_an_event(cx: &mut TestAppContext) {
let (app, tx, _) = entity(cx);
let notified = std::rc::Rc::new(std::cell::Cell::new(0));
let _subscription = cx.update(|cx| {
let notified = notified.clone();
cx.observe(&app, move |_, _| notified.set(notified.get() + 1))
});
tx.send(voice(VoiceState::Connecting)).unwrap();
cx.run_until_parked();
assert_eq!(notified.get(), 1);
}
#[gpui::test]
fn the_tick_runs_once_a_second(cx: &mut TestAppContext) {
let (app, _tx, counters) = entity(cx);
cx.run_until_parked();
assert_eq!(app.read_with(cx, |app, _| app.ticks), 0);
for second in 1..=3 {
cx.executor().advance_clock(Duration::from_secs(1));
cx.run_until_parked();
assert_eq!(app.read_with(cx, |app, _| app.ticks), second);
}
assert_eq!(counters.ticks.get(), 3);
}
#[gpui::test]
fn another_thread_runs_a_job_on_the_entity_through_later(cx: &mut TestAppContext) {
let (app, _tx, counters) = entity(cx);
let later = app.read_with(cx, |app, _| app.later());
let sent = std::thread::spawn(move || {
later.run(|app, _| app.vm.status = "from another thread".into())
})
.join()
.unwrap();
assert!(sent);
cx.run_until_parked();
assert_eq!(app.read_with(cx, |app, _| app.vm.status.clone()), "from another thread");
assert_eq!(counters.later_jobs.get(), 1);
}
#[gpui::test]
fn a_job_sent_after_the_window_went_is_dropped_and_the_next_one_is_refused(
cx: &mut TestAppContext,
) {
let (app, _tx, counters) = entity(cx);
let later = app.read_with(cx, |app, _| app.later());
drop(app);
cx.update(|_| {});
cx.run_until_parked();
assert!(later.run(|_, _| {}), "queued: nothing has found the entity gone yet");
cx.run_until_parked();
assert_eq!(counters.later_jobs.get(), 0, "never run");
assert!(!later.run(|_, _| {}), "the first job found the entity gone");
}
/// What closing the window hands the runtime's shutdown: the number of
/// sessions the engine was told to close, which `run` gives time to act
/// on (the Slint front end does the same). The engine ignores a close for
/// a session it never opened, so the sessions here are only the state's.
#[gpui::test]
fn closing_counts_the_sessions_the_engine_was_told_to_close(cx: &mut TestAppContext) {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
let hosted = HostedEngine::start(&runtime);
let (tx, rx) = mpsc::unbounded_channel();
let app =
cx.new(|cx| AppState::new(Some(hosted.engine.clone()), rx, Counters::default(), cx));
assert_eq!(app.read_with(cx, |app, _| app.shutdown()), 0, "no session open yet");
tx.send(voice(VoiceState::Connected)).unwrap();
cx.run_until_parked();
assert_eq!(app.read_with(cx, |app, _| app.shutdown()), 1);
runtime.shutdown_timeout(Duration::from_secs(2));
}
#[gpui::test]
fn closing_without_an_engine_tells_nothing(cx: &mut TestAppContext) {
let (app, tx, _) = entity(cx);
tx.send(voice(VoiceState::Connected)).unwrap();
cx.run_until_parked();
assert_eq!(app.read_with(cx, |app, _| (app.connections(), app.shutdown())), (1, 0));
}
/// The whole path with a real engine: a command makes the engine report a
/// setting change, which its forwarder hands to the window's channel and
/// the foreground task to the entity. The engine's tasks run on tokio
/// threads, so the test looks again until the event is in (no bound on
/// how long the loaded machine takes, a generous one on the whole wait);
/// the test scheduler is told that other threads wake it
/// (`allow_parking`), which it otherwise reports as a test that is not
/// deterministic.
#[gpui::test]
fn a_real_engine_event_reaches_the_entity(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
let hosted = HostedEngine::start(&runtime);
let engine = hosted.engine.clone();
let counters = Counters::default();
let app = cx.new(|cx| AppState::new(Some(engine.clone()), hosted.events, counters, cx));
engine.send(Command::SetSetting { key: "stream.fps".into(), value: 144.into() });
let deadline = Instant::now() + Duration::from_secs(120);
while app.read_with(cx, |app, _| app.events_handled) == 0 {
assert!(Instant::now() < deadline, "the engine's event never arrived");
cx.run_until_parked();
std::thread::sleep(Duration::from_millis(10));
}
assert!(app.read_with(cx, |app, _| app.events_handled) >= 1);
runtime.shutdown_timeout(Duration::from_secs(2));
}
}
+79
View File
@@ -0,0 +1,79 @@
//! What `svg()` and gpui-component's `Icon` load by path. The client's own
//! Lucide 1.48 icons (the 147 SVGs of the Slint front end, embedded by
//! `build.rs`) answer `icons/<name>.svg` first, so every widget draws the
//! icons the client draws; anything else (the rest of gpui-kit-assets'
//! Lucide 1.43 catalogue, which gpui-component's `IconName` names) comes from
//! gpui-kit-assets.
use std::borrow::Cow;
use gpui_kit::{AssetSource, Result, SharedString};
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
/// The client's icons first, then gpui-kit-assets'.
#[derive(Clone, Copy, Debug, Default)]
pub struct Assets;
/// The client's icon of a file name (`mic.svg`), if it has one.
pub fn client_icon(name: &str) -> Option<&'static [u8]> {
ICONS.binary_search_by_key(&name, |(n, _)| n).ok().map(|i| ICONS[i].1)
}
/// The names of the client's icons, sorted.
pub fn client_icon_names() -> impl Iterator<Item = &'static str> {
ICONS.iter().map(|(name, _)| *name)
}
impl AssetSource for Assets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
if let Some(bytes) = path.strip_prefix("icons/").and_then(client_icon) {
return Ok(Some(Cow::Borrowed(bytes)));
}
gpui_kit::assets::AllAssets.load(path)
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
gpui_kit::assets::AllAssets.list(path)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_client_set_is_embedded_and_sorted() {
assert!(ICONS.len() >= 140, "{} icons", ICONS.len());
assert!(ICONS.windows(2).all(|pair| pair[0].0 < pair[1].0));
for (name, bytes) in ICONS {
assert!(std::str::from_utf8(bytes).is_ok_and(|text| text.contains("<svg")), "{name}");
}
}
#[test]
fn the_client_icon_answers_before_gpui_kit_assets() {
let name = client_icon_names().find(|n| *n == "mic.svg").expect("the client has a mic");
let ours = client_icon(name).unwrap();
let kit = gpui_kit::assets::AllAssets
.load(&format!("icons/{name}"))
.unwrap()
.expect("gpui-kit-assets has a mic too");
let served = Assets.load(&format!("icons/{name}")).unwrap().unwrap();
assert_eq!(&*served, ours);
assert_ne!(&*kit, ours, "Lucide 1.43 and 1.48 draw it differently, or this test is moot");
}
#[test]
fn other_icons_and_other_paths_fall_through_to_gpui_kit_assets() {
let kit = gpui_kit::assets::AllAssets.list("icons/").unwrap();
let only_in_kit = kit
.iter()
.find(|path| client_icon(path.trim_start_matches("icons/")).is_none())
.expect("the catalogue has icons the client lacks");
assert!(Assets.load(only_in_kit).unwrap().is_some(), "{only_in_kit}");
// gpui-kit-assets answers a path it does not have with an error, so do we.
assert!(Assets.load("icons/no-such-icon.svg").is_err());
assert!(Assets.load("nothing/here").is_err());
}
}
+143
View File
@@ -0,0 +1,143 @@
//! The development switches of the GPUI front end, read from the
//! environment. They are the Slint front end's (docs/ui.md, "Development
//! switches and screenshots") where the GPUI one has the same thing to
//! switch, so that one recipe serves both; the rest are new.
//!
//! - `VOELIN_OPEN=swatch`: the swatch page (every theme token, a few
//! components, the icons) in place of the shell. The Slint front end's
//! other pages do not exist here yet; they are named in a warning and
//! skipped.
//! - `VOELIN_DEV_THEME=dark|light|system`: the theme mode, in place of the
//! one the settings will give (`ui.theme` in the Slint front end).
//! - `VOELIN_FONT_SCALE=1.25`: the text size factor (`ui.font_scale`).
//! - `VOELIN_WINDOW_SIZE=1440x960`: the window's size.
//! - `VOELIN_METER=1`: the cost meter, one log line a second
//! ([`crate::meter`]).
use crate::theme::Choice;
/// A page the window can be opened on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Page {
/// The shell. Today an empty window with the state line.
Shell,
/// Every theme token, a few components and the icons.
Swatch,
}
/// What the environment switched.
#[derive(Clone, Debug, PartialEq)]
pub struct Switches {
/// The page to open on.
pub open: Page,
/// The theme mode, when the switch names one.
pub theme: Option<Choice>,
/// The text size factor, when the switch names one.
pub font_scale: Option<f32>,
/// The window's size in pixels, when the switch names one.
pub window: Option<(f32, f32)>,
/// Log the cost meter.
pub meter: bool,
}
impl Default for Switches {
fn default() -> Self {
Self { open: Page::Shell, theme: None, font_scale: None, window: None, meter: false }
}
}
impl Switches {
/// The switches of this process's environment.
pub fn from_env() -> Self {
Self::parse(|name| std::env::var(name).ok())
}
/// The switches `get` answers for; what it does not understand is logged
/// and left out.
pub fn parse(get: impl Fn(&str) -> Option<String>) -> Self {
let mut switches = Self::default();
if let Some(list) = get("VOELIN_OPEN") {
for what in list.split(',').map(str::trim).filter(|w| !w.is_empty()) {
match what {
"swatch" => switches.open = Page::Swatch,
other => tracing::warn!(
"VOELIN_OPEN={other}: this page is not in the GPUI front end yet (swatch is)"
),
}
}
}
if let Some(name) = get("VOELIN_DEV_THEME") {
match Choice::parse(name.trim()) {
Some(choice) => switches.theme = Some(choice),
None => tracing::warn!("VOELIN_DEV_THEME={name}: dark, light or system"),
}
}
if let Some(text) = get("VOELIN_FONT_SCALE") {
match text.trim().parse::<f32>() {
Ok(scale) if (0.5..=3.0).contains(&scale) => switches.font_scale = Some(scale),
_ => tracing::warn!("VOELIN_FONT_SCALE={text}: a number from 0.5 to 3"),
}
}
if let Some(text) = get("VOELIN_WINDOW_SIZE") {
match parse_size(&text) {
Some(size) => switches.window = Some(size),
None => tracing::warn!("VOELIN_WINDOW_SIZE={text}: WIDTHxHEIGHT, such as 1440x960"),
}
}
switches.meter = get("VOELIN_METER").is_some_and(|v| !matches!(v.trim(), "" | "0"));
switches
}
}
/// `WIDTHxHEIGHT` in pixels, at least 320 by 240 and at most 16384 each way.
fn parse_size(text: &str) -> Option<(f32, f32)> {
let (w, h) = text.trim().split_once('x')?;
let (w, h): (u32, u32) = (w.parse().ok()?, h.parse().ok()?);
((320..=16384).contains(&w) && (240..=16384).contains(&h)).then_some((w as f32, h as f32))
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use super::*;
fn env(pairs: &[(&str, &str)]) -> Switches {
let map: HashMap<String, String> =
pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
Switches::parse(|name| map.get(name).cloned())
}
#[test]
fn nothing_switched_is_the_shell_in_the_settings_theme() {
assert_eq!(env(&[]), Switches::default());
}
#[test]
fn every_switch_is_read() {
let s = env(&[
("VOELIN_OPEN", "swatch"),
("VOELIN_DEV_THEME", "light"),
("VOELIN_FONT_SCALE", "1.25"),
("VOELIN_WINDOW_SIZE", "1440x960"),
("VOELIN_METER", "1"),
]);
assert_eq!(s.open, Page::Swatch);
assert_eq!(s.theme, Some(Choice::Light));
assert_eq!(s.font_scale, Some(1.25));
assert_eq!(s.window, Some((1440.0, 960.0)));
assert!(s.meter);
}
#[test]
fn what_makes_no_sense_is_left_out() {
let s = env(&[
("VOELIN_OPEN", "settings:voice,home"),
("VOELIN_DEV_THEME", "blue"),
("VOELIN_FONT_SCALE", "9"),
("VOELIN_WINDOW_SIZE", "10x10"),
("VOELIN_METER", "0"),
]);
assert_eq!(s, Switches::default());
}
}
+45
View File
@@ -0,0 +1,45 @@
//! The engine this front end runs on, the same one the Slint front end
//! hosts (`voelin_ui::HostedEngine`, `crates/voelin-ui/src/app.rs`): started
//! on a tokio runtime, its events forwarded into a channel the window reads.
//! The Slint crate cannot be a dependency here (it brings Slint in), so the
//! few lines are repeated; both go into `voelin-ui-vm` when the Slint front
//! end is retired.
use tokio::runtime::{Handle, Runtime};
use tokio::sync::{broadcast, mpsc};
use voelin_core::{Engine, Event};
/// An engine owned by the caller of [`crate::run`].
pub struct HostedEngine {
/// The handle: commands go in through it.
pub engine: Engine,
/// The runtime the engine runs on; the window's helpers run there too.
pub runtime: Handle,
/// The engine's events for the window: first those that rebuild the
/// current state of every session, then new ones. Reading them needs no
/// reactor, so the window's foreground executor can await it.
pub events: mpsc::UnboundedReceiver<Event>,
}
impl HostedEngine {
/// A new engine on `runtime`, all of whose events go to the window.
pub fn start(runtime: &Runtime) -> Self {
let engine = runtime.block_on(async { Engine::start() });
let (tx, events) = mpsc::unbounded_channel();
let mut rx = engine.subscribe();
runtime.spawn(async move {
loop {
match rx.recv().await {
Ok(event) => {
if tx.send(event).is_err() {
break;
}
}
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(_) => break,
}
}
});
Self { engine, runtime: runtime.handle().clone(), events }
}
}
+39
View File
@@ -0,0 +1,39 @@
//! Inter, the UI font, as the Slint front end bundles it
//! (`crates/voelin-ui/ui/assets/fonts`, OFL): the five files go into GPUI's
//! text system and are used by family name ([`crate::theme::FONT_FAMILY`]),
//! so nothing depends on what fontconfig finds for Latin text. Colour emoji
//! come later (the chat slice; docs/design/gpui-spikes.md, "Open choices for step 3").
use std::borrow::Cow;
use gpui_kit::App;
/// The files of the family: regular, medium, semibold, bold, italic.
const INTER: [&[u8]; 5] = [
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Regular.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Medium.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-SemiBold.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Bold.ttf"),
include_bytes!("../../voelin-ui/ui/assets/fonts/Inter-Italic.ttf"),
];
/// Add Inter to GPUI's text system.
pub fn load(cx: &mut App) {
let fonts: Vec<Cow<'static, [u8]>> = INTER.iter().map(|bytes| Cow::Borrowed(*bytes)).collect();
if let Err(error) = cx.text_system().add_fonts(fonts) {
tracing::warn!(%error, "cannot add Inter to the text system");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_files_are_fonts() {
for bytes in INTER {
assert!(bytes.len() > 100_000, "a font file, not {} bytes", bytes.len());
assert!(matches!(&bytes[..4], [0, 1, 0, 0] | b"OTTO" | b"true"), "an sfnt header");
}
}
}
+182
View File
@@ -0,0 +1,182 @@
//! The GPUI front end of the desktop app, under construction (plan section 6
//! of the migration from Slint; docs/ui.md, "The GPUI front end"). The Slint
//! front end (`voelin-ui`, the `voelin` binary) stays the app until this one
//! reaches parity; both run on the same engine.
#![warn(missing_docs)]
pub mod app;
pub mod assets;
pub mod dev;
pub mod engine;
pub mod fonts;
pub mod meter;
pub mod swatch;
pub mod theme;
pub mod view;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::Duration;
use anyhow::{Context as _, Result};
use gpui_kit::{App, AppContext as _, TitlebarOptions, WindowBounds, WindowOptions, px, size};
use tracing_subscriber::{EnvFilter, fmt, prelude::*};
use crate::app::AppState;
use crate::assets::Assets;
use crate::dev::Switches;
use crate::engine::HostedEngine;
use crate::meter::Counters;
use crate::theme::{Choice, VoelinTheme};
use crate::view::MainView;
/// How long the engine gets, after the window closed, to act on the
/// `CloseSession` commands the close sent (the Slint front end waits as long):
/// its tasks run on the runtime, and shutting the runtime down drops them.
const CLOSE_GRACE: Duration = Duration::from_millis(500);
/// What the log gets without `VOELIN_LOG` or `RUST_LOG`: warnings of every
/// crate, this front end's information, and what GPUI says about the display
/// and the GPU adapter it picked (which device a run used). Two warnings are
/// left out because they are harmless: zbus's, as in the Slint front end (it
/// warns when a desktop portal's request object is gone before it reads its
/// properties), and GPUI's "failed to load font .SystemUIFont" (gpui-component
/// asks for the platform's UI font, which Linux has no name for, before the
/// theme names Inter; the text system falls back).
const LOG_FILTER: &str =
"warn,zbus=error,gpui::text_system=error,voelin_gpui=info,gpui_wgpu=info,gpui_linux=info";
/// Log to the terminal: `VOELIN_LOG`, else `RUST_LOG`, else [`LOG_FILTER`].
/// GPUI logs through the `log` crate; the subscriber carries those records.
pub fn init_logging() {
let filter = EnvFilter::try_from_env("VOELIN_LOG")
.or_else(|_| EnvFilter::try_from_default_env())
.unwrap_or_else(|_| EnvFilter::new(LOG_FILTER));
let _ = tracing_subscriber::registry()
.with(fmt::layer().with_writer(std::io::stderr).with_filter(filter))
.try_init();
}
/// The main window's options: titled with the app's name, grouped by its id,
/// centred, 1280 by 800 unless `VOELIN_WINDOW_SIZE` says otherwise.
fn window_options(switches: &Switches, cx: &App) -> WindowOptions {
let (width, height) = switches.window.unwrap_or((1280.0, 800.0));
WindowOptions {
titlebar: Some(TitlebarOptions {
title: Some(voelin_platform::APP_NAME.into()),
..Default::default()
}),
app_id: Some(voelin_platform::APP_ID.to_owned()),
window_min_size: Some(size(px(640.0), px(480.0))),
window_bounds: Some(WindowBounds::centered(size(px(width), px(height)), cx)),
..Default::default()
}
}
/// Open the main window on the root state; closing it leaves the servers and
/// ends the app. `closed_sessions` is set to how many sessions the close told
/// the engine to close, which [`run`] needs after GPUI's loop has ended.
fn open_main_window(
cx: &mut App,
switches: &Switches,
engine: HostedEngine,
counters: Counters,
closed_sessions: Rc<Cell<usize>>,
) -> Result<()> {
// Without a display server GPUI falls back to a headless platform, which
// opens windows that draw nothing and runs until it is stopped.
if cx.compositor_name() == "headless" {
return Err(anyhow::anyhow!(
"no display: neither DISPLAY nor WAYLAND_DISPLAY names a display server"
))
.context("cannot open the main window");
}
let HostedEngine { engine, events, .. } = engine;
let app = cx.new({
let counters = counters.clone();
move |cx| AppState::new(Some(engine), events, counters, cx)
});
let options = window_options(switches, cx);
let page = switches.open;
gpui_kit::open_window(options, cx, {
let app = app.clone();
move |window, cx| {
// The window's own appearance, which may differ from the system's before
// the window exists.
VoelinTheme::set_system_appearance(cx, window.appearance());
window.on_window_should_close(cx, {
let app = app.clone();
move |_, cx| {
closed_sessions.set(app.read(cx).shutdown());
cx.quit();
true
}
});
cx.new(|cx| MainView::new(app, page, counters, window, cx))
}
})
.context("cannot open the main window")?;
Ok(())
}
/// Run the app on the current thread until its window closes.
pub fn run() -> Result<()> {
init_logging();
let switches = Switches::from_env();
tracing::info!(
version = env!("CARGO_PKG_VERSION"),
os = std::env::consts::OS,
"Voelin (GPUI) starting"
);
let counters = Counters::default();
if switches.meter {
meter::start(counters.clone());
}
// The engine runs on tokio threads of its own; the window is GPUI's.
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.context("cannot start the engine's runtime")?;
let hosted = HostedEngine::start(&runtime);
let failure: Rc<RefCell<Option<anyhow::Error>>> = Rc::default();
let closed_sessions: Rc<Cell<usize>> = Rc::default();
gpui_kit::application().with_assets(Assets).run({
let failure = failure.clone();
let closed_sessions = closed_sessions.clone();
move |cx| {
gpui_kit::init(cx);
fonts::load(cx);
// Until the settings are read here (the shell slice), the mode and
// the text size are the development switches' or the defaults.
VoelinTheme::init(
cx,
switches.theme.unwrap_or(Choice::System),
cx.window_appearance(),
switches.font_scale.unwrap_or(1.0),
);
if let Err(e) = open_main_window(cx, &switches, hosted, counters, closed_sessions) {
*failure.borrow_mut() = Some(e);
// Not `cx.quit()` here: GPUI's Linux platform runs this callback
// before it starts its event loop, and the loop forgets a stop
// asked for earlier (calloop clears its stop signal when it
// starts), so the process would stay with no window and no
// message. A task runs inside the loop.
cx.spawn(async move |cx| cx.update(|cx| cx.quit())).detach();
}
}
});
// The close told the engine to close the sessions; give its tasks time to
// send that before the runtime drops them (`shutdown_timeout` waits for
// blocking tasks only), as the Slint front end does, or ghost clients stay
// on the servers until they time out. Any other way to end the app that
// the slices add must call `AppState::shutdown` too.
if closed_sessions.get() > 0 {
runtime.block_on(tokio::time::sleep(CLOSE_GRACE));
}
runtime.shutdown_timeout(Duration::from_secs(2));
match failure.take() {
Some(e) => Err(e),
None => Ok(()),
}
}
+6
View File
@@ -0,0 +1,6 @@
//! `voelin-gpui`: the GPUI front end of the desktop app (docs/ui.md, "The
//! GPUI front end").
fn main() -> anyhow::Result<()> {
voelin_gpui::run()
}
+303
View File
@@ -0,0 +1,303 @@
//! What the app costs, once a second, in the log: the CPU of the process and
//! of each group of threads, the resident memory, and the app's own counters
//! (a development switch, `VOELIN_METER=1`, so that every slice can say what
//! it costs). It is `spike_common::meter` of the GPUI spikes
//! (`spikes/gpui/common/src/meter.rs`, docs/design/gpui-spikes.md) without the
//! measuring run's summary and exit, writing log lines instead of JSON.
//!
//! CPU is in percent of one core (200 means two cores busy). Threads are
//! grouped by name without a trailing number (`llvmpipe-12` becomes
//! `llvmpipe`), which tells the software renderer's share (Mesa's `llvmpipe-*`
//! threads, work a GPU would take over) from GPUI's thread, the engine's
//! runtime and the codecs. The numbers come from `/proc/self`: on other
//! systems the meter says it cannot read them and stops.
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
/// A number the app counts up (events handled, frames drawn) or sets (open
/// connections); the meter reports counters per second and gauges as they
/// are.
#[derive(Clone, Default, Debug)]
pub struct Counter(Arc<AtomicU64>);
impl Counter {
/// Add one.
pub fn incr(&self) {
self.0.fetch_add(1, Ordering::Relaxed);
}
/// Set (gauges).
pub fn set(&self, value: u64) {
self.0.store(value, Ordering::Relaxed);
}
/// The current value.
pub fn get(&self) -> u64 {
self.0.load(Ordering::Relaxed)
}
}
/// The app's own numbers the meter reports besides the process's.
#[derive(Clone, Default, Debug)]
pub struct Counters {
/// Engine events handled by the root state (per second).
pub engine_events: Counter,
/// One-second ticks of the root state (per second: 1).
pub ticks: Counter,
/// Windows drawn (frames, per second).
pub renders: Counter,
/// Jobs other threads handed to the foreground through
/// [`crate::app::Later`] (per second).
pub later_jobs: Counter,
/// Voice connections that are up (a gauge).
pub connections: Counter,
}
/// CPU ticks of the process and of each thread group, and the resident
/// memory, at one moment.
#[derive(Clone, Debug)]
pub struct Snapshot {
at: Instant,
process: u64,
threads: BTreeMap<String, u64>,
rss_bytes: u64,
}
/// The size of a page of memory, for `statm`'s page counts.
#[cfg(target_os = "linux")]
fn page_size() -> u64 {
rustix::param::page_size() as u64
}
/// The size of a page of memory (Linux only matters: `/proc`).
#[cfg(not(target_os = "linux"))]
fn page_size() -> u64 {
4096
}
/// The unit of the CPU times in `stat`.
#[cfg(target_os = "linux")]
fn clock_ticks_per_second() -> u64 {
rustix::param::clock_ticks_per_second()
}
/// The unit of the CPU times in `stat` (Linux only matters: `/proc`).
#[cfg(not(target_os = "linux"))]
fn clock_ticks_per_second() -> u64 {
100
}
/// `utime + stime` and the name of a `/proc/.../stat` line.
fn ticks_of(stat: &str) -> Option<(String, u64)> {
let open = stat.find('(')?;
let close = stat.rfind(')')?;
let name = stat.get(open + 1..close)?.to_owned();
let fields: Vec<&str> = stat.get(close + 1..)?.split_whitespace().collect();
// Fields 14 and 15 of proc(5); the remainder starts at field 3.
let utime: u64 = fields.get(11)?.parse().ok()?;
let stime: u64 = fields.get(12)?.parse().ok()?;
Some((name, utime + stime))
}
/// A thread's group: its name without a trailing number or separator.
pub fn group_of(name: &str) -> String {
let trimmed = name.trim_end_matches(|c: char| c.is_ascii_digit());
let trimmed = trimmed.trim_end_matches(['-', '_', ':', ' ', '#']);
if trimmed.is_empty() { name.to_owned() } else { trimmed.to_owned() }
}
impl Snapshot {
/// Read `/proc/self` now; `None` where there is none.
pub fn now() -> Option<Self> {
let process = std::fs::read_to_string("/proc/self/stat").ok().and_then(|s| ticks_of(&s))?.1;
let mut threads = BTreeMap::new();
if let Ok(dir) = std::fs::read_dir("/proc/self/task") {
for entry in dir.flatten() {
let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else { continue };
if let Some((name, ticks)) = ticks_of(&stat) {
*threads.entry(group_of(&name)).or_insert(0) += ticks;
}
}
}
let rss_bytes = std::fs::read_to_string("/proc/self/statm")
.ok()
.and_then(|s| s.split_whitespace().nth(1)?.parse::<u64>().ok())
.map_or(0, |pages| pages * page_size());
Some(Self { at: Instant::now(), process, threads, rss_bytes })
}
/// Resident memory in MiB.
pub fn rss_mib(&self) -> f64 {
self.rss_bytes as f64 / (1024.0 * 1024.0)
}
}
/// CPU in percent of one core between two snapshots: the process's and each
/// thread group's that used any (groups that exited in between count from
/// zero).
pub fn cpu_between(a: &Snapshot, b: &Snapshot) -> (f64, BTreeMap<String, f64>) {
let hz = clock_ticks_per_second() as f64;
let secs = b.at.duration_since(a.at).as_secs_f64().max(1e-6);
let pct = |ticks: u64| ticks as f64 / hz / secs * 100.0;
let process = pct(b.process.saturating_sub(a.process));
let threads = b
.threads
.iter()
.map(|(name, &t)| (name.clone(), pct(t.saturating_sub(*a.threads.get(name).unwrap_or(&0)))))
.filter(|(_, p)| *p > 0.0)
.collect();
(process, threads)
}
/// One second of the meter as a log line: `cpu 42.0% rss 210.4 MiB threads
/// llvmpipe 31.0 main 5.0 | engine_events 0.0/s ... | connections 1`.
pub fn line(
cpu: f64,
rss_mib: f64,
threads: &BTreeMap<String, f64>,
rates: &[(&str, f64)],
gauges: &[(&str, u64)],
) -> String {
let mut text = format!("cpu {cpu:.1}% rss {rss_mib:.1} MiB");
// The busiest groups first; a thread group under 0.5 % is noise.
let mut busy: Vec<(&String, &f64)> = threads.iter().filter(|(_, p)| **p >= 0.5).collect();
busy.sort_by(|a, b| b.1.total_cmp(a.1).then_with(|| a.0.cmp(b.0)));
if !busy.is_empty() {
text.push_str(" | threads");
for (name, pct) in busy {
let _ = write!(text, " {name} {pct:.1}");
}
}
text.push_str(" |");
for (name, rate) in rates {
let _ = write!(text, " {name} {rate:.1}/s");
}
if !gauges.is_empty() {
text.push_str(" |");
for (name, value) in gauges {
let _ = write!(text, " {name} {value}");
}
}
text
}
/// Start the meter on a thread of its own: once a second, a log line (target
/// `voelin_gpui::meter`, level info) with the process's CPU and memory and
/// `counters`' rates. It ends with the process.
pub fn start(counters: Counters) {
let spawned = std::thread::Builder::new().name("voelin-meter".into()).spawn(move || {
let Some(mut last) = Snapshot::now() else {
tracing::warn!(target: "voelin_gpui::meter", "the meter reads /proc/self; there is none here");
return;
};
let rated = [
("engine_events", counters.engine_events.clone()),
("ticks", counters.ticks.clone()),
("renders", counters.renders.clone()),
("later_jobs", counters.later_jobs.clone()),
];
let mut last_counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
tracing::info!(target: "voelin_gpui::meter", "meter on: one line a second (VOELIN_METER)");
loop {
std::thread::sleep(Duration::from_secs(1));
let Some(now) = Snapshot::now() else { return };
let secs = now.at.duration_since(last.at).as_secs_f64().max(1e-6);
let (cpu, threads) = cpu_between(&last, &now);
let counts: Vec<u64> = rated.iter().map(|(_, c)| c.get()).collect();
let rates: Vec<(&str, f64)> = rated
.iter()
.zip(counts.iter().zip(&last_counts))
.map(|((name, _), (c, l))| (*name, c.saturating_sub(*l) as f64 / secs))
.collect();
let gauges = [("connections", counters.connections.get())];
tracing::info!(
target: "voelin_gpui::meter",
"{}",
line(cpu, now.rss_mib(), &threads, &rates, &gauges)
);
last = now;
last_counts = counts;
}
});
if let Err(error) = spawned {
tracing::warn!(target: "voelin_gpui::meter", %error, "no meter thread");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn groups_drop_trailing_numbers() {
assert_eq!(group_of("llvmpipe-12"), "llvmpipe");
assert_eq!(group_of("tokio-runtime-w"), "tokio-runtime-w");
assert_eq!(group_of("voelin-meter"), "voelin-meter");
assert_eq!(group_of("1234"), "1234");
}
#[test]
fn stat_lines_parse_with_spaces_in_names() {
let line = "42 (a b) c) S 1 2 3 4 5 6 7 8 9 10 100 23 0 0 20 0 1 0 0";
assert_eq!(ticks_of(line), Some(("a b) c".to_owned(), 123)));
}
#[test]
fn the_line_names_the_busiest_threads_first_and_hides_the_idle_ones() {
let threads = BTreeMap::from([
("main".to_owned(), 5.04),
("llvmpipe".to_owned(), 310.0),
("idle".to_owned(), 0.2),
]);
let text = line(
317.0,
210.44,
&threads,
&[("engine_events", 0.0), ("renders", 59.96)],
&[("connections", 1)],
);
assert_eq!(
text,
"cpu 317.0% rss 210.4 MiB | threads llvmpipe 310.0 main 5.0 | engine_events 0.0/s renders 60.0/s | connections 1"
);
}
#[test]
fn this_process_can_be_read_on_linux() {
if !cfg!(target_os = "linux") {
return;
}
let a = Snapshot::now().expect("/proc/self");
// The kernel counts a process's CPU in ticks of 10 ms, and on a busy
// machine this thread gets a tick's worth of CPU only after a long wall
// time: burn CPU until a second reading shows the process's ticks above
// the first, and in a thread group (the process's total and a thread's
// own are rounded separately). The deadline only ends a hang
// (docs/testing/load.md); it never decides the result.
let deadline = Instant::now() + Duration::from_secs(30);
let (b, cpu) = loop {
let burn = Instant::now();
let mut x = 0u64;
while burn.elapsed() < Duration::from_millis(2) {
x = x.wrapping_mul(31).wrapping_add(7);
}
std::hint::black_box(x);
let b = Snapshot::now().expect("/proc/self");
let (cpu, threads) = cpu_between(&a, &b);
if b.process > a.process && !threads.is_empty() {
break (b, cpu);
}
assert!(
Instant::now() < deadline,
"no CPU tick showed in 30 s: {} -> {}",
a.process,
b.process
);
};
assert!(cpu > 0.0 && b.rss_mib() > 1.0, "{cpu} {}", b.rss_mib());
}
}
+389
View File
@@ -0,0 +1,389 @@
//! The swatch page: every colour token of the theme with its name and value,
//! the radii, the spacing, the type scale, a few gpui-component widgets (drawn
//! from the second layer of the theme) and the client's icons, in the mode
//! the theme is in. A development page (`VOELIN_OPEN=swatch`): the screenshots
//! of a theme change, and what the screenshots in docs/ui/ show.
use std::collections::HashMap;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::checkbox::Checkbox;
use gpui_kit::component::switch::Switch;
use gpui_kit::{
FontWeight, InteractiveElement as _, IntoElement, ParentElement as _,
StatefulInteractiveElement as _, Styled as _, div, px, svg,
};
use crate::theme::{VoelinTheme, hsla, tokens::Rgba};
/// The colour tokens by the groups of docs/ui.md's "Theme tokens" table.
pub const GROUPS: [(&str, &[&str]); 6] = [
(
"Backgrounds",
&[
"bg-app",
"bg-rail",
"surface",
"surface-2",
"surface-3",
"surface-4",
"scrim",
"scrim-light",
"overlay",
],
),
("Lines", &["border", "border-strong", "border-popup", "glow"]),
(
"Accent",
&[
"accent",
"accent-hover",
"accent-pressed",
"accent-soft",
"accent-soft-hover",
"accent-text",
"name-text",
"on-accent",
],
),
(
"States",
&[
"live",
"live-soft",
"danger",
"danger-soft",
"success",
"success-soft",
"warning",
"warning-soft",
"idle",
"dnd",
"offline",
"gold",
"info",
],
),
("Text", &["text", "text-secondary", "text-muted", "text-disabled", "icon"]),
("Meter", &["meter-low", "meter-mid", "meter-high", "meter-off"]),
];
/// Icons shown, by the name of the client's file.
const ICONS: [&str; 16] = [
"mic.svg",
"mic-off.svg",
"headphones.svg",
"volume-2.svg",
"settings.svg",
"search.svg",
"bell.svg",
"users.svg",
"message-square.svg",
"monitor-up.svg",
"hash.svg",
"lock.svg",
"crown.svg",
"plus.svg",
"x.svg",
"check.svg",
];
fn heading(theme: &VoelinTheme, text: &str) -> impl IntoElement {
let m = &theme.metrics;
div()
.text_size(px(m.font_md))
.font_weight(FontWeight::SEMIBOLD)
.text_color(hsla(theme.colors.text))
.child(text.to_owned())
}
fn chip(theme: &VoelinTheme, name: &str, color: Rgba) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.w(px(100.0))
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.h(px(24.0))
.rounded(px(m.radius_xs))
.border_1()
.border_color(hsla(c.border_strong))
.bg(hsla(color)),
)
.child(
div()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_secondary))
.child(name.to_owned()),
)
.child(
div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(color.to_string()),
)
}
fn colours(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let by_name: HashMap<&str, Rgba> = c.entries().into_iter().collect();
let mut column = div().flex().flex_col().gap(px(m.space_4));
for (group, names) in GROUPS {
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_3));
for name in names {
row = row.child(chip(theme, name, by_name[name]));
}
column = column.child(
div().flex().flex_col().gap(px(m.space_2)).child(heading(theme, group)).child(row),
);
}
column
}
fn radii(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let mut row = div().flex().flex_row().gap(px(m.space_4));
for (name, radius) in [
("xs", m.radius_xs),
("sm", m.radius_sm),
("md", m.radius_md),
("lg", m.radius_lg),
("xl", m.radius_xl),
("pill", m.radius_pill),
] {
row = row.child(
div()
.flex()
.flex_col()
.items_center()
.gap(px(m.space_2))
.child(
div()
.size(px(40.0))
.rounded(px(radius))
.bg(hsla(c.surface_4))
.border_1()
.border_color(hsla(c.border_popup)),
)
.child(div().text_size(px(m.font_xs)).text_color(hsla(c.text_muted)).child(name)),
);
}
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Radii")).child(row)
}
fn spacing(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let mut rows = div().flex().flex_col().gap(px(m.space_1));
for (name, space) in [
("space-1", m.space_1),
("space-2", m.space_2),
("space-3", m.space_3),
("space-4", m.space_4),
("space-5", m.space_5),
("space-6", m.space_6),
("space-7", m.space_7),
("space-8", m.space_8),
] {
rows = rows.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_3))
.child(
div()
.w(px(56.0))
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(name),
)
.child(div().h(px(6.0)).w(px(space * 4.0)).rounded(px(2.0)).bg(hsla(c.accent)))
.child(
div()
.text_size(px(m.font_xs))
.text_color(hsla(c.text_muted))
.child(format!("{space} px")),
),
);
}
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Spacing")).child(rows)
}
fn type_scale(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let mut rows = div().flex().flex_col();
for (name, size, weight) in [
("font-3xl", m.font_3xl, FontWeight::BOLD),
("font-2xl", m.font_2xl, FontWeight::SEMIBOLD),
("font-xl", m.font_xl, FontWeight::SEMIBOLD),
("font-lg", m.font_lg, FontWeight::MEDIUM),
("font-md", m.font_md, FontWeight::MEDIUM),
("font-body", m.font_body, FontWeight::NORMAL),
("font-sm", m.font_sm, FontWeight::NORMAL),
("font-xs", m.font_xs, FontWeight::NORMAL),
] {
rows = rows.child(
div()
.text_size(px(size))
.font_weight(weight)
.text_color(hsla(c.text))
.child(format!("{name} {size}: Raid tonight at 21:00")),
);
}
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Type")).child(rows)
}
fn components(theme: &VoelinTheme) -> impl IntoElement {
let m = &theme.metrics;
div()
.flex()
.flex_col()
.gap(px(m.space_3))
.child(heading(theme, "Components (gpui-component, through ThemeColor)"))
.child(
div()
.flex()
.flex_row()
.flex_wrap()
.gap(px(m.space_3))
.child(Button::new("primary").primary().label("Primary"))
.child(Button::new("secondary").label("Secondary"))
.child(Button::new("danger").danger().label("Danger"))
.child(Button::new("success").success().label("Success"))
.child(Button::new("warning").warning().label("Warning"))
.child(Button::new("info").info().label("Info")),
)
.child(
div()
.flex()
.flex_row()
.items_center()
.gap(px(m.space_5))
.child(Switch::new("on").checked(true))
.child(Switch::new("off").checked(false))
.child(Checkbox::new("checked").checked(true).label("Checked"))
.child(Checkbox::new("unchecked").checked(false).label("Unchecked")),
)
}
fn backdrop(theme: &VoelinTheme) -> impl IntoElement {
let (c, m, b) = (&theme.colors, &theme.metrics, &theme.backdrop);
let [first, _, last] = b.stops;
div().flex().flex_col().gap(px(m.space_3)).child(heading(theme, "Backdrop")).child(
div()
.h(px(36.0))
.rounded(px(m.radius_md))
.border_1()
.border_color(hsla(c.border))
.bg(b.to_gpui())
.px(px(m.space_3))
.py(px(m.space_2))
.text_size(px(m.font_xs))
.text_color(hsla(c.text_secondary))
.child(format!(
"{}deg: {} to {}; the middle stop, {} at {}%, is not drawn",
b.angle,
first.0,
last.0,
b.stops[1].0,
(b.stops[1].1 * 100.0).round()
)),
)
}
fn icons(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
let mut row = div().flex().flex_row().flex_wrap().gap(px(m.space_5));
for name in ICONS {
row = row.child(
svg().path(format!("icons/{name}")).size(px(m.icon_lg)).text_color(hsla(c.icon)),
);
}
div()
.flex()
.flex_col()
.gap(px(m.space_3))
.child(heading(theme, "Icons (the client's Lucide 1.48, as gpui-component's icons/ paths)"))
.child(row)
}
/// The page: the colours on the left, the rest on the right; it scrolls when
/// the window is smaller than it.
pub fn swatch(theme: &VoelinTheme) -> impl IntoElement {
let (c, m) = (&theme.colors, &theme.metrics);
div()
.id("swatch")
.size_full()
.overflow_y_scroll()
.flex()
.flex_col()
.gap(px(m.space_4))
.p(px(m.space_6))
.bg(hsla(c.bg_app))
.child(
div()
.flex()
.flex_row()
.items_baseline()
.gap(px(m.space_4))
.child(
div()
.text_size(px(m.font_2xl))
.font_weight(FontWeight::BOLD)
.text_color(hsla(c.text))
.child("Voelin theme"),
)
.child(div().text_size(px(m.font_sm)).text_color(hsla(c.text_muted)).child(
format!(
"{} (setting {}), text size {}",
if theme.is_dark() { "dark" } else { "light" },
theme.choice().name(),
m.font_scale
),
)),
)
.child(
div()
.flex()
.flex_row()
.gap(px(m.space_8))
.child(div().w(px(752.0)).flex_none().child(colours(theme)))
.child(
div()
.w(px(600.0))
.flex()
.flex_col()
.gap(px(m.space_4))
.child(backdrop(theme))
.child(radii(theme))
.child(spacing(theme))
.child(type_scale(theme))
.child(components(theme))
.child(icons(theme)),
),
)
}
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use super::*;
use crate::assets::client_icon;
use crate::theme::Palette;
#[test]
fn every_colour_token_is_in_exactly_one_group() {
let shown: Vec<&str> = GROUPS.iter().flat_map(|(_, names)| names.iter().copied()).collect();
let unique: BTreeSet<&str> = shown.iter().copied().collect();
assert_eq!(shown.len(), unique.len(), "a token in two groups");
let tokens: BTreeSet<&str> = Palette::DARK.entries().into_iter().map(|(n, _)| n).collect();
assert_eq!(unique, tokens);
}
#[test]
fn the_icons_shown_are_the_clients() {
for name in ICONS {
assert!(client_icon(name).is_some(), "{name}");
}
}
}
+278
View File
@@ -0,0 +1,278 @@
//! The second layer of the theme: the colours gpui-component's widgets read,
//! written from the Voelin palette. gpui-component's `ThemeColor` is shadcn's
//! vocabulary (about 135 colours: a background, a primary, a muted, one set
//! for the list, one for the table, one for each kind of button); the
//! client's tokens map onto it as docs/ui.md ("The GPUI front end") lists.
//! What has no counterpart stays as the registered theme of the mode has it
//! (charts' bullish and bearish colours, the cyan and magenta of the base
//! palette).
//!
//! gpui-component's "accent" is a hover background, not a brand colour: the
//! client's `accent` is its `primary`.
use gpui_kit::Hsla;
use gpui_kit::component::ThemeColor;
use super::tokens::{Palette, Rgba};
/// A palette colour as GPUI's.
pub fn hsla(color: Rgba) -> Hsla {
gpui_kit::rgba(color.0).into()
}
/// Of `base`, the colours a status button needs: hover, active, and a text
/// that reads on it (white or the window's ink, whichever contrasts more).
struct Status {
base: Hsla,
hover: Hsla,
active: Hsla,
foreground: Hsla,
}
fn status(base: Rgba, ink: Rgba, dark: bool) -> Status {
let toward_hover = if dark { Rgba(0xffff_ffff) } else { Rgba(0x0000_00ff) };
Status {
base: hsla(base),
hover: hsla(base.mix(toward_hover, 0.14)),
active: hsla(base.mix(Rgba(0x0000_00ff), 0.18)),
foreground: hsla(base.readable(ink)),
}
}
/// Write the palette's colours into `colors`, over what the registered theme
/// of the mode left there. Every field that gpui-component's themes derive
/// from another (the buttons fall back to `primary`, `danger`, ...) is written
/// too, so that none keeps the default theme's blue.
pub fn write(p: &Palette, dark: bool, colors: &mut ThemeColor) {
let c = colors;
let h = hsla;
let clear = Hsla::transparent_black();
// The window and its text.
c.background = h(p.bg_app);
c.foreground = h(p.text);
c.border = h(p.border);
c.input = h(p.border_strong);
c.ring = h(p.glow);
c.overlay = h(p.scrim);
c.window_border = h(p.border);
c.caret = h(p.text);
c.selection = h(p.accent_soft);
c.drag_border = h(p.accent);
c.drop_target = h(p.accent_soft);
// Links: one colour for all three states, as the client has one.
c.link = h(p.accent_text);
c.link_hover = h(p.accent_text);
c.link_active = h(p.accent_text);
// The brand colour, and gpui-component's hover "accent".
c.primary = h(p.accent);
c.primary_hover = h(p.accent_hover);
c.primary_active = h(p.accent_pressed);
c.primary_foreground = h(p.on_accent);
c.accent = h(p.surface_3);
c.accent_foreground = h(p.text);
// Cards, inputs, menus, popovers.
c.secondary = h(p.surface_2);
c.secondary_hover = h(p.surface_3);
c.secondary_active = h(p.surface_4);
c.secondary_foreground = h(p.text);
c.muted = h(p.surface_2);
c.muted_foreground = h(p.text_muted);
c.popover = h(p.surface_3);
c.popover_foreground = h(p.text);
c.group_box = h(p.surface_2);
c.group_box_foreground = h(p.text);
c.accordion = h(p.surface_2);
c.description_list_label = h(p.surface_2);
c.description_list_label_foreground = h(p.text_secondary);
// The status colours, with the text that reads on each.
let [danger, success, warning, info] =
[p.danger, p.success, p.warning, p.info].map(|base| status(base, p.bg_app, dark));
(c.danger, c.danger_hover, c.danger_active, c.danger_foreground) =
(danger.base, danger.hover, danger.active, danger.foreground);
(c.success, c.success_hover, c.success_active, c.success_foreground) =
(success.base, success.hover, success.active, success.foreground);
(c.warning, c.warning_hover, c.warning_active, c.warning_foreground) =
(warning.base, warning.hover, warning.active, warning.foreground);
(c.info, c.info_hover, c.info_active, c.info_foreground) =
(info.base, info.hover, info.active, info.foreground);
// Lists and tables: rows on the panel, hovered rows raised, the selected
// row the soft accent with the accent's edge.
c.list = h(p.surface);
c.list_hover = h(p.surface_3);
c.list_active = h(p.accent_soft);
c.list_active_border = h(p.accent);
c.list_even = h(p.surface);
c.list_head = h(p.surface_2);
c.table = h(p.surface);
c.table_hover = h(p.surface_3);
c.table_active = h(p.accent_soft);
c.table_active_border = h(p.accent);
c.table_even = h(p.surface);
c.table_head = h(p.surface_2);
c.table_head_foreground = h(p.text_secondary);
c.table_foot = h(p.surface_2);
c.table_foot_foreground = h(p.text_secondary);
c.table_row_border = h(p.border);
// The panels around the content: the sidebar, the title and status bars.
c.sidebar = h(p.surface);
c.sidebar_foreground = h(p.text);
c.sidebar_border = h(p.border);
c.sidebar_accent = h(p.surface_3);
c.sidebar_accent_foreground = h(p.text);
c.sidebar_primary = h(p.accent);
c.sidebar_primary_foreground = h(p.on_accent);
c.title_bar = h(p.surface);
c.title_bar_border = h(p.border);
c.status_bar = h(p.surface);
c.status_bar_border = h(p.border);
// Small widgets.
c.scrollbar = clear;
c.scrollbar_thumb = h(p.border_strong);
c.scrollbar_thumb_hover = h(p.text_muted);
c.slider_bar = h(p.accent);
c.slider_thumb = h(p.on_accent);
c.switch = h(p.surface_4);
c.switch_thumb = h(p.on_accent);
c.progress_bar = h(p.accent);
c.skeleton = h(p.surface_3);
c.tab = clear;
c.tab_active = h(p.surface_2);
c.tab_active_foreground = h(p.text);
c.tab_bar = h(p.surface);
c.tab_bar_segmented = h(p.surface_2);
c.tab_foreground = h(p.text_secondary);
// The base palette and the charts: the client's state colours.
c.red = h(p.danger);
c.red_light = h(p.danger_soft);
c.green = h(p.success);
c.green_light = h(p.success_soft);
c.yellow = h(p.warning);
c.yellow_light = h(p.warning_soft);
c.blue = h(p.info);
c.blue_light = h(p.accent_soft);
c.chart_1 = h(p.accent);
c.chart_2 = h(p.success);
c.chart_3 = h(p.warning);
c.chart_4 = h(p.danger);
c.chart_5 = h(p.info);
// The buttons: what a theme file leaves out they take from the colours
// above, so they are written from them here.
c.button = c.secondary;
c.button_hover = c.secondary_hover;
c.button_active = c.secondary_active;
c.button_foreground = c.secondary_foreground;
c.button_primary = c.primary;
c.button_primary_hover = c.primary_hover;
c.button_primary_active = c.primary_active;
c.button_primary_foreground = c.primary_foreground;
c.button_secondary = c.secondary;
c.button_secondary_hover = c.secondary_hover;
c.button_secondary_active = c.secondary_active;
c.button_secondary_foreground = c.secondary_foreground;
c.button_danger = c.danger;
c.button_danger_hover = c.danger_hover;
c.button_danger_active = c.danger_active;
c.button_danger_foreground = c.danger_foreground;
c.button_success = c.success;
c.button_success_hover = c.success_hover;
c.button_success_active = c.success_active;
c.button_success_foreground = c.success_foreground;
c.button_warning = c.warning;
c.button_warning_hover = c.warning_hover;
c.button_warning_active = c.warning_active;
c.button_warning_foreground = c.warning_foreground;
c.button_info = c.info;
c.button_info_hover = c.info_hover;
c.button_info_active = c.info_active;
c.button_info_foreground = c.info_foreground;
}
#[cfg(test)]
mod tests {
use super::*;
fn written(dark: bool) -> (Palette, ThemeColor) {
let palette = if dark { Palette::DARK } else { Palette::LIGHT };
let mut colors = ThemeColor::default();
write(&palette, dark, &mut colors);
(palette, colors)
}
#[test]
fn the_client_tokens_land_where_the_table_says() {
for dark in [true, false] {
let (p, c) = written(dark);
assert_eq!(c.background, hsla(p.bg_app));
assert_eq!(c.foreground, hsla(p.text));
assert_eq!(c.primary, hsla(p.accent));
assert_eq!(c.primary_hover, hsla(p.accent_hover));
assert_eq!(c.primary_active, hsla(p.accent_pressed));
assert_eq!(c.primary_foreground, hsla(p.on_accent));
assert_eq!(
c.accent,
hsla(p.surface_3),
"gpui-component's accent is a hover background"
);
assert_eq!(c.secondary, hsla(p.surface_2));
assert_eq!(c.secondary_active, hsla(p.surface_4));
assert_eq!(c.border, hsla(p.border));
assert_eq!(c.input, hsla(p.border_strong));
assert_eq!(c.ring, hsla(p.glow));
assert_eq!(c.overlay, hsla(p.scrim));
assert_eq!(c.list_active, hsla(p.accent_soft));
assert_eq!(c.link, hsla(p.accent_text));
assert_eq!(c.muted_foreground, hsla(p.text_muted));
assert_eq!(c.sidebar, hsla(p.surface));
assert_eq!(c.danger, hsla(p.danger));
assert_eq!(c.success, hsla(p.success));
}
}
#[test]
fn the_buttons_follow_the_colours_they_fall_back_to() {
let (_, c) = written(true);
assert_eq!(c.button_primary, c.primary);
assert_eq!(c.button_primary_hover, c.primary_hover);
assert_eq!(c.button_danger_foreground, c.danger_foreground);
assert_eq!(c.button, c.secondary);
assert_eq!(c.button_info_active, c.info_active);
}
#[test]
fn the_text_on_a_status_colour_is_the_one_that_reads_better() {
for (p, dark) in [(Palette::DARK, true), (Palette::LIGHT, false)] {
for base in [p.danger, p.success, p.warning, p.info] {
let s = status(base, p.bg_app, dark);
let chosen = base.readable(p.bg_app);
let other = if chosen == Rgba(0xffff_ffff) { p.bg_app } else { Rgba(0xffff_ffff) };
assert!(base.contrast(chosen) >= base.contrast(other), "{base} on {chosen}");
assert_eq!(s.foreground, hsla(chosen));
assert_ne!(s.hover, s.base);
assert_ne!(s.active, s.base);
}
}
}
#[test]
fn mixing_and_contrast_do_what_they_say() {
let (black, white) = (Rgba(0x0000_00ff), Rgba(0xffff_ffff));
assert_eq!(black.mix(white, 0.0), black);
assert_eq!(black.mix(white, 1.0), white);
assert_eq!(Rgba(0x1020_30c0).mix(white, 0.0), Rgba(0x1020_30c0), "opacity stays");
assert!((black.contrast(white) - 21.0).abs() < 0.01);
assert_eq!(black.readable(black), white);
assert_eq!(Rgba(0xf5b3_01ff).readable(Rgba(0x060a_18ff)), Rgba(0x060a_18ff));
assert_eq!(Rgba(0x12ab_34ff).to_string(), "#12ab34");
assert_eq!(Rgba(0x12ab_3480).to_string(), "#12ab3480");
}
}
+293
View File
@@ -0,0 +1,293 @@
//! The Voelin theme, in two layers (docs/ui.md, "The GPUI front end"):
//!
//! 1. [`VoelinTheme`], a GPUI global with every token of
//! `crates/voelin-ui/ui/theme.slint`, light and dark ([`tokens`]), which a
//! test keeps equal to the Slint file ([`slint_parity`]). The shell's own
//! elements (the server rail, presence dots, meters, the backdrop) read it.
//! 2. gpui-component's `ThemeColor`, the colours its widgets (inputs, lists,
//! menus, dialogs) read, written from the first on every change
//! ([`components`]), so that they look like ours.
//!
//! The mode is the client's `ui.theme`: `system` follows the window's
//! appearance (and its changes), `light` and `dark` do not.
mod components;
#[cfg(test)]
mod slint_parity;
pub mod tokens;
pub use components::hsla;
use gpui_kit::component::{Theme, ThemeMode};
use gpui_kit::{App, Background, Global, WindowAppearance, linear_color_stop, linear_gradient, px};
pub use tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
impl Backdrop {
/// What GPUI draws: its gradient has two colour stops, so the first and the
/// last of the three; the middle one is not drawn.
pub fn to_gpui(&self) -> Background {
let [first, _, last] = self.stops;
linear_gradient(
self.angle,
linear_color_stop(hsla(first.0), first.1),
linear_color_stop(hsla(last.0), last.1),
)
}
}
/// The theme mode setting (`ui.theme` of the Slint front end).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Choice {
/// Follow the window's appearance.
System,
/// Always light.
Light,
/// Always dark.
Dark,
}
impl Choice {
/// `system`, `light` or `dark`.
pub fn parse(text: &str) -> Option<Self> {
match text {
"system" => Some(Self::System),
"light" => Some(Self::Light),
"dark" => Some(Self::Dark),
_ => None,
}
}
/// The setting's value.
pub fn name(self) -> &'static str {
match self {
Self::System => "system",
Self::Light => "light",
Self::Dark => "dark",
}
}
/// Whether the theme is dark, given whether the window's appearance is.
pub fn resolve(self, system_dark: bool) -> bool {
match self {
Self::System => system_dark,
Self::Light => false,
Self::Dark => true,
}
}
}
/// Whether a window's appearance is a dark one.
pub fn is_dark(appearance: WindowAppearance) -> bool {
matches!(appearance, WindowAppearance::Dark | WindowAppearance::VibrantDark)
}
/// Every token of `theme.slint` for the resolved mode and text size; a GPUI
/// global.
#[derive(Clone, Debug)]
pub struct VoelinTheme {
choice: Choice,
dark: bool,
/// The colours of the resolved mode.
pub colors: Palette,
/// The window's backdrop gradient of the resolved mode.
pub backdrop: Backdrop,
/// The sizes, radii, type and durations at the text size factor.
pub metrics: Metrics,
}
impl Global for VoelinTheme {}
impl VoelinTheme {
/// The tokens for a mode (resolved against `system_dark`) and a text size
/// factor.
pub fn new(choice: Choice, system_dark: bool, font_scale: f32) -> Self {
let dark = choice.resolve(system_dark);
Self {
choice,
dark,
colors: if dark { Palette::DARK } else { Palette::LIGHT },
backdrop: if dark { Backdrop::DARK } else { Backdrop::LIGHT },
metrics: Metrics::new(font_scale),
}
}
/// The theme mode that was set.
pub fn choice(&self) -> Choice {
self.choice
}
/// Whether the colours are the dark ones.
pub fn is_dark(&self) -> bool {
self.dark
}
/// Install the theme as the global and write it into gpui-component, which
/// `gpui_kit::init` must have set up. `appearance` is the window's (or
/// the system's before there is a window).
pub fn init(cx: &mut App, choice: Choice, appearance: WindowAppearance, font_scale: f32) {
cx.set_global(Self::new(choice, is_dark(appearance), font_scale));
Self::apply(cx);
}
/// The theme global.
pub fn global(cx: &App) -> &Self {
cx.global::<Self>()
}
/// Change the mode (a setting changed), given the window's appearance now.
pub fn set_choice(cx: &mut App, choice: Choice, appearance: WindowAppearance) {
let (scale, current) = {
let this = Self::global(cx);
(this.metrics.font_scale, this.choice)
};
if current == choice && Self::global(cx).dark == choice.resolve(is_dark(appearance)) {
return;
}
cx.set_global(Self::new(choice, is_dark(appearance), scale));
Self::apply(cx);
}
/// The window's appearance changed; it matters only in `system` mode.
pub fn set_system_appearance(cx: &mut App, appearance: WindowAppearance) {
let this = Self::global(cx);
if this.choice == Choice::System && this.dark != is_dark(appearance) {
let (choice, scale) = (this.choice, this.metrics.font_scale);
cx.set_global(Self::new(choice, is_dark(appearance), scale));
Self::apply(cx);
}
}
/// The text size factor changed (`ui.font_scale`).
pub fn set_font_scale(cx: &mut App, font_scale: f32) {
let this = Self::global(cx);
if (this.metrics.font_scale - font_scale).abs() < f32::EPSILON {
return;
}
// `dark` is what the mode resolved to: for every mode, resolving it again
// against it gives the same.
let (choice, dark) = (this.choice, this.dark);
cx.set_global(Self::new(choice, dark, font_scale));
Self::apply(cx);
}
/// Write the global into gpui-component's theme: the mode, the colours of
/// the second layer, the font, the base size and the radii.
fn apply(cx: &mut App) {
let this = Self::global(cx).clone();
// The registered theme of the mode first (it sets whatever the second
// layer leaves alone), then our colours over it in a second update, as
// `Theme::update` says a mode change must be.
Theme::change(if this.dark { ThemeMode::Dark } else { ThemeMode::Light }, None, cx);
Theme::update(cx, |theme| {
components::write(&this.colors, this.dark, &mut theme.colors);
theme.font_family = FONT_FAMILY.into();
theme.font_size = px(this.metrics.font_body);
theme.radius = px(this.metrics.radius_sm);
theme.radius_lg = px(this.metrics.radius_lg);
});
// Where the platform draws the window's frame itself (macOS), it follows
// the mode; elsewhere this does nothing.
cx.set_window_appearance(match this.choice {
Choice::System => None,
Choice::Light => Some(WindowAppearance::Light),
Choice::Dark => Some(WindowAppearance::Dark),
});
}
}
#[cfg(test)]
mod tests {
use gpui::TestAppContext;
use gpui_kit::component::ActiveTheme as _;
use super::*;
fn start(cx: &mut TestAppContext, choice: Choice, appearance: WindowAppearance) {
cx.update(|cx| {
gpui_kit::init(cx);
VoelinTheme::init(cx, choice, appearance, 1.0);
});
}
#[test]
fn the_mode_resolves_against_the_window() {
assert!(Choice::System.resolve(true) && !Choice::System.resolve(false));
assert!(Choice::Dark.resolve(false) && !Choice::Light.resolve(true));
for choice in [Choice::System, Choice::Light, Choice::Dark] {
assert_eq!(Choice::parse(choice.name()), Some(choice));
}
assert_eq!(Choice::parse("blue"), None);
assert!(is_dark(WindowAppearance::VibrantDark) && !is_dark(WindowAppearance::VibrantLight));
}
#[test]
fn the_backdrop_draws_the_first_and_the_last_of_its_three_stops() {
let b = Backdrop::DARK;
let [first, middle, last] = b.stops;
assert_eq!(
b.to_gpui(),
linear_gradient(
160.0,
linear_color_stop(hsla(first.0), 0.0),
linear_color_stop(hsla(last.0), 1.0)
)
);
assert_ne!(
b.to_gpui(),
linear_gradient(
160.0,
linear_color_stop(hsla(first.0), 0.0),
linear_color_stop(hsla(middle.0), 1.0)
),
"the middle stop is not the end one"
);
}
#[gpui::test]
fn the_tokens_reach_gpui_component(cx: &mut TestAppContext) {
start(cx, Choice::Dark, WindowAppearance::Light);
cx.update(|cx| {
let theme = cx.theme();
assert!(theme.is_dark());
assert_eq!(theme.colors.primary, hsla(Palette::DARK.accent));
assert_eq!(theme.colors.background, hsla(Palette::DARK.bg_app));
assert_eq!(theme.colors.button_primary, hsla(Palette::DARK.accent));
assert_eq!(theme.font_family.as_ref(), "Inter");
assert_eq!(theme.font_size, px(14.0));
assert_eq!(theme.radius, px(6.0));
assert_eq!(theme.radius_lg, px(12.0));
assert_eq!(VoelinTheme::global(cx).colors, Palette::DARK);
assert_eq!(VoelinTheme::global(cx).backdrop, Backdrop::DARK);
});
}
#[gpui::test]
fn system_follows_the_window_appearance_and_light_and_dark_do_not(cx: &mut TestAppContext) {
start(cx, Choice::System, WindowAppearance::Light);
let primary = |cx: &mut TestAppContext| cx.update(|cx| cx.theme().colors.primary);
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Dark));
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::VibrantLight));
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent));
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Dark, WindowAppearance::Light));
assert_eq!(primary(cx), hsla(Palette::DARK.accent));
cx.update(|cx| VoelinTheme::set_system_appearance(cx, WindowAppearance::Light));
assert_eq!(primary(cx), hsla(Palette::DARK.accent), "a dark choice ignores the window");
cx.update(|cx| VoelinTheme::set_choice(cx, Choice::Light, WindowAppearance::Dark));
assert_eq!(primary(cx), hsla(Palette::LIGHT.accent), "so does a light one");
}
#[gpui::test]
fn the_text_size_scales_the_type_and_the_controls(cx: &mut TestAppContext) {
start(cx, Choice::Dark, WindowAppearance::Dark);
cx.update(|cx| VoelinTheme::set_font_scale(cx, 1.25));
cx.update(|cx| {
let theme = VoelinTheme::global(cx);
assert!(theme.is_dark(), "the mode stays");
assert_eq!(theme.metrics.font_body, 17.5);
assert_eq!(theme.metrics.control_height, 45.0);
assert_eq!(cx.theme().font_size, px(17.5));
});
}
}
@@ -0,0 +1,318 @@
//! `crates/voelin-ui/ui/theme.slint` against `tokens.rs`: the Slint file is
//! read and every token in it is compared with the Rust value of the same
//! name, light and dark and at four text sizes; a token on one side only, a
//! value that differs, or a declaration of a kind this test does not know
//! (or a second brush or string, of which it knows `backdrop`, `mode` and
//! `font-family`) fails it. While both front ends live, a token changed in
//! one place and not the other is caught here.
use std::collections::{BTreeMap, BTreeSet};
use super::tokens::{Backdrop, FONT_FAMILY, Metrics, Palette, Rgba};
const SLINT: &str = include_str!("../../../voelin-ui/ui/theme.slint");
/// What `theme.slint` declares: the kind and the expression of each property
/// of the `Theme` global, in file order.
fn declarations() -> Vec<(String, String, String)> {
declarations_of(SLINT)
}
/// The same for the text of a `.slint` file (the tests below also read
/// altered copies of `theme.slint`).
fn declarations_of(source: &str) -> Vec<(String, String, String)> {
let without_comments: String = source
.lines()
.map(|line| line.split("//").next().unwrap_or(""))
.collect::<Vec<_>>()
.join("\n");
let body = without_comments.split_once("export global Theme {").expect("the Theme global").1;
let mut found = Vec::new();
for statement in body.split(';') {
let statement = statement.trim();
let Some(rest) = ["in-out property", "out property", "in property"]
.iter()
.find_map(|prefix| statement.strip_prefix(prefix))
else {
continue;
};
let (kind, rest) =
rest.trim().strip_prefix('<').expect("<kind>").split_once('>').expect("<kind>");
let (name, expr) = rest.trim().split_once(':').expect("name: expression");
// One line, single spaces: `backdrop` is written over several.
let expr = expr.split_whitespace().collect::<Vec<_>>().join(" ");
found.push((name.trim().to_owned(), kind.trim().to_owned(), expr));
}
found
}
/// `#rgb`-style literal as `Rgba`.
fn colour(text: &str) -> Rgba {
let hex = text.trim().strip_prefix('#').unwrap_or_else(|| panic!("a colour, not {text:?}"));
let value = u32::from_str_radix(hex, 16).unwrap_or_else(|_| panic!("hex digits in {text:?}"));
match hex.len() {
6 => Rgba(value << 8 | 0xff),
8 => Rgba(value),
_ => panic!("#rrggbb or #rrggbbaa, not {text:?}"),
}
}
/// Split `dark ? A : B` at its top-level `?` and `:`; `A` for a plain `A`.
fn by_mode(expr: &str) -> (String, String) {
let Some(rest) = expr.strip_prefix("dark ?") else {
return (expr.to_owned(), expr.to_owned());
};
let mut depth = 0;
for (i, c) in rest.char_indices() {
match c {
'(' => depth += 1,
')' => depth -= 1,
':' if depth == 0 => {
return (rest[..i].trim().to_owned(), rest[i + 1..].trim().to_owned());
}
_ => {}
}
}
panic!("no `:` in {expr:?}");
}
/// The arithmetic of the length tokens: numbers with a unit, other tokens,
/// `*`, `+`, `max(a, b)` and parentheses.
struct Eval<'a> {
tokens: Vec<String>,
at: usize,
env: &'a BTreeMap<String, String>,
scale: f64,
}
impl<'a> Eval<'a> {
fn run(expr: &str, env: &'a BTreeMap<String, String>, scale: f64) -> f64 {
let mut tokens = Vec::new();
let mut word = String::new();
for c in expr.chars() {
if c.is_alphanumeric() || matches!(c, '-' | '.' | '%') {
word.push(c);
} else {
if !word.is_empty() {
tokens.push(std::mem::take(&mut word));
}
if !c.is_whitespace() {
tokens.push(c.to_string());
}
}
}
if !word.is_empty() {
tokens.push(word);
}
let mut eval = Eval { tokens, at: 0, env, scale };
let value = eval.sum();
assert_eq!(eval.at, eval.tokens.len(), "all of {expr:?} is read");
value
}
fn peek(&self) -> Option<&str> {
self.tokens.get(self.at).map(String::as_str)
}
fn take(&mut self) -> String {
self.at += 1;
self.tokens[self.at - 1].clone()
}
fn sum(&mut self) -> f64 {
let mut value = self.product();
while self.peek() == Some("+") {
self.take();
value += self.product();
}
value
}
fn product(&mut self) -> f64 {
let mut value = self.factor();
while self.peek() == Some("*") {
self.take();
value *= self.factor();
}
value
}
fn factor(&mut self) -> f64 {
let token = self.take();
if token == "(" {
let value = self.sum();
assert_eq!(self.take(), ")");
return value;
}
if token == "max" {
assert_eq!(self.take(), "(");
let a = self.sum();
assert_eq!(self.take(), ",");
let b = self.sum();
assert_eq!(self.take(), ")");
return a.max(b);
}
if token == "font-scale" {
return self.scale;
}
if token.starts_with(|c: char| c.is_ascii_digit()) {
let number: String =
token.chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();
return number.parse().unwrap_or_else(|_| panic!("a number in {token:?}"));
}
let expr =
self.env.get(&token).unwrap_or_else(|| panic!("a token named {token:?}")).clone();
Eval::run(&expr, self.env, self.scale)
}
}
/// The names `theme.slint` declares that are state, not tokens: the mode and
/// what it resolves to, and the text size factor (the factor is a parameter
/// of [`Metrics`]).
const STATE: [&str; 4] = ["mode", "system-dark", "dark", "font-scale"];
#[test]
fn every_colour_is_the_same_in_both_files() {
let slint: Vec<(String, String, String)> =
declarations().into_iter().filter(|(_, kind, _)| kind == "color").collect();
assert!(slint.len() > 40, "the colours were found: {}", slint.len());
let dark: BTreeMap<_, _> = Palette::DARK.entries().into_iter().collect();
let light: BTreeMap<_, _> = Palette::LIGHT.entries().into_iter().collect();
let mut names = BTreeSet::new();
for (name, _, expr) in &slint {
let (d, l) = by_mode(expr);
assert_eq!(dark.get(name.as_str()), Some(&colour(&d)), "{name} (dark)");
assert_eq!(light.get(name.as_str()), Some(&colour(&l)), "{name} (light)");
names.insert(name.as_str());
}
let ours: BTreeSet<&str> = dark.keys().copied().collect();
assert_eq!(ours, names, "colours in tokens.rs and not in theme.slint, or the other way");
}
#[test]
fn every_length_weight_and_duration_is_the_same_in_both_files() {
let all = declarations();
let env: BTreeMap<String, String> =
all.iter().map(|(name, _, expr)| (name.clone(), expr.clone())).collect();
let numeric: Vec<&(String, String, String)> = all
.iter()
.filter(|(name, kind, _)| {
matches!(kind.as_str(), "length" | "int" | "duration")
&& !STATE.contains(&name.as_str())
})
.collect();
assert!(numeric.len() > 30, "the numbers were found: {}", numeric.len());
for scale in [1.0_f32, 1.25, 0.8, 2.0] {
let ours: BTreeMap<&str, f64> = Metrics::new(scale).entries().into_iter().collect();
let mut names = BTreeSet::new();
for (name, _, expr) in &numeric {
let slint = Eval::run(expr, &env, f64::from(scale));
let ours = *ours.get(name.as_str()).unwrap_or_else(|| panic!("{name} is in tokens.rs"));
assert!(
(slint - ours).abs() < 1e-3,
"{name} at {scale}: theme.slint {slint}, tokens.rs {ours}"
);
names.insert(name.as_str());
}
let rust: BTreeSet<&str> = ours.keys().copied().collect();
assert_eq!(rust, names, "numbers in tokens.rs and not in theme.slint, or the other way");
}
}
#[test]
fn the_backdrop_and_the_font_are_the_same_in_both_files() {
let all = declarations();
let get = |name: &str| {
all.iter().find(|(n, _, _)| n == name).unwrap_or_else(|| panic!("{name}")).2.clone()
};
let gradient = |text: &str| -> Backdrop {
let inner = text
.trim()
.strip_prefix("@linear-gradient(")
.and_then(|t| t.strip_suffix(')'))
.unwrap_or_else(|| panic!("a linear gradient, not {text:?}"));
let mut parts = inner.split(',').map(str::trim);
let angle: f32 = parts.next().unwrap().trim_end_matches("deg").parse().unwrap();
let stops: Vec<(Rgba, f32)> = parts
.map(|stop| {
let (colour_text, position) = stop.split_once(' ').unwrap();
let percent: f32 = position.trim().trim_end_matches('%').parse().unwrap();
(colour(colour_text), percent / 100.0)
})
.collect();
Backdrop { angle, stops: stops.try_into().expect("three stops") }
};
let (dark, light) = by_mode(&get("backdrop"));
assert_eq!(gradient(&dark), Backdrop::DARK);
assert_eq!(gradient(&light), Backdrop::LIGHT);
assert_eq!(get("font-family"), format!("\"{FONT_FAMILY}\""));
}
/// What the declarations hold that no comparison above covers, one sentence
/// each; empty when there is none: a kind of declaration this test does not
/// know, a brush other than `backdrop` or a string other than `mode` and
/// `font-family` (the two comparisons of those go by name, so a second one
/// would pass unseen), a state name that is no longer declared.
fn unknown_to_this_test(declared: &[(String, String, String)]) -> Vec<String> {
let mut problems = Vec::new();
let kinds: BTreeSet<&str> = declared
.iter()
.filter(|(name, _, _)| !STATE.contains(&name.as_str()))
.map(|(_, kind, _)| kind.as_str())
.collect();
let known = BTreeSet::from(["color", "brush", "length", "int", "duration", "string"]);
if kinds != known {
problems.push(format!("kinds of declaration {kinds:?}, this test knows {known:?}"));
}
for (kind, expected) in [("brush", &["backdrop"][..]), ("string", &["mode", "font-family"])] {
let found: BTreeSet<&str> = declared
.iter()
.filter(|(_, declared_kind, _)| declared_kind == kind)
.map(|(name, _, _)| name.as_str())
.collect();
let expected: BTreeSet<&str> = expected.iter().copied().collect();
for name in found.symmetric_difference(&expected) {
problems.push(format!(
"{name}: the <{kind}> declarations are {found:?}, this test compares {expected:?}"
));
}
}
for name in STATE {
if !declared.iter().any(|(declared, _, _)| declared == name) {
problems.push(format!("{name} is not declared"));
}
}
problems
}
#[test]
fn the_file_declares_nothing_this_test_does_not_know() {
let problems = unknown_to_this_test(&declarations());
assert!(problems.is_empty(), "{problems:#?}");
}
/// `theme.slint` with one more declaration in its `Theme` global.
fn with_declaration(declaration: &str) -> String {
let opening = "export global Theme {";
assert!(SLINT.contains(opening));
SLINT.replacen(opening, &format!("{opening}\n {declaration}"), 1)
}
#[test]
fn a_second_brush_or_string_is_not_passed_unseen() {
// Mutants of the Slint file: a token on one side only.
for (declaration, name) in [
("out property <brush> backdrop-soft: #123456;", "backdrop-soft"),
("out property <string> font-mono: \"Mono\";", "font-mono"),
] {
let mutant = declarations_of(&with_declaration(declaration));
assert!(mutant.iter().any(|(declared, _, _)| declared == name), "the mutant has {name}");
let problems = unknown_to_this_test(&mutant);
assert!(
problems.iter().any(|problem| problem.contains(name)),
"{name} goes unnoticed: {problems:#?}"
);
}
// And the file as it is has neither.
assert_eq!(unknown_to_this_test(&declarations()), Vec::<String>::new());
}
+372
View File
@@ -0,0 +1,372 @@
//! The tokens of `crates/voelin-ui/ui/theme.slint`, light and dark, as Rust
//! values: the source of truth the GPUI front end copies. `theme.slint` stays
//! the original while the Slint front end lives; the test in
//! `theme/slint_parity.rs` reads it and fails when a value, a name or a
//! formula here differs from it, so the two cannot drift apart.
use std::fmt;
/// A colour as `0xRRGGBBAA`, as the Slint file writes `#rrggbbaa` (`#rrggbb`
/// is opaque).
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Rgba(pub u32);
impl fmt::Debug for Rgba {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}
impl fmt::Display for Rgba {
/// `#rrggbb`, or `#rrggbbaa` when not opaque.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.alpha() == 255 {
write!(f, "#{:06x}", self.0 >> 8)
} else {
write!(f, "#{:08x}", self.0)
}
}
}
impl Rgba {
/// Transparent black, for the widgets that draw nothing.
pub const TRANSPARENT: Self = Self(0);
/// The opacity, 0 to 255.
pub fn alpha(self) -> u8 {
(self.0 & 0xff) as u8
}
/// The same colour with another opacity.
pub fn with_alpha(self, alpha: u8) -> Self {
Self((self.0 & 0xffff_ff00) | u32::from(alpha))
}
/// The channels, 0 to 1.
pub fn channels(self) -> [f32; 3] {
[24, 16, 8].map(|shift| ((self.0 >> shift) & 0xff) as f32 / 255.0)
}
/// Mixed with `other` (of `amount`, 0 to 1), channel by channel, opacity
/// from `self`.
pub fn mix(self, other: Self, amount: f32) -> Self {
let (a, b) = (self.channels(), other.channels());
let channel =
|i: usize| ((a[i] + (b[i] - a[i]) * amount) * 255.0).round().clamp(0.0, 255.0) as u32;
Self(channel(0) << 24 | channel(1) << 16 | channel(2) << 8 | u32::from(self.alpha()))
}
/// The relative luminance of WCAG 2, 0 (black) to 1 (white).
pub fn luminance(self) -> f32 {
let [r, g, b] = self
.channels()
.map(|c| if c <= 0.03928 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) });
0.2126 * r + 0.7152 * g + 0.0722 * b
}
/// The contrast ratio of WCAG 2 between two colours, 1 to 21.
pub fn contrast(self, other: Self) -> f32 {
let (a, b) = (self.luminance(), other.luminance());
(a.max(b) + 0.05) / (a.min(b) + 0.05)
}
/// Of white and `ink`, the one that reads better on `self`.
pub fn readable(self, ink: Self) -> Self {
let white = Self(0xffff_ffff);
if self.contrast(white) >= self.contrast(ink) { white } else { ink }
}
}
macro_rules! palette {
($($field:ident $name:literal: $dark:literal, $light:literal;)*) => {
/// Every colour token of `theme.slint` for one mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Palette {
$(
#[doc = concat!("`", $name, "` of `theme.slint`.")]
pub $field: Rgba,
)*
}
impl Palette {
/// The dark palette.
pub const DARK: Self = Self { $($field: Rgba($dark),)* };
/// The light palette.
pub const LIGHT: Self = Self { $($field: Rgba($light),)* };
/// Every colour by the name it has in `theme.slint`, in its order.
pub fn entries(&self) -> Vec<(&'static str, Rgba)> {
vec![$(($name, self.$field),)*]
}
}
};
}
palette! {
bg_app "bg-app": 0x060a18ff, 0xe9eef9ff;
bg_rail "bg-rail": 0x070c1dff, 0xdfe6f4ff;
surface "surface": 0x0b1330ff, 0xf7f9feff;
surface_2 "surface-2": 0x101a3cff, 0xffffffff;
surface_3 "surface-3": 0x16224bff, 0xeaf0fbff;
surface_4 "surface-4": 0x1c2b5cff, 0xdce5f7ff;
scrim "scrim": 0x02050fc0, 0x0b132b80;
scrim_light "scrim-light": 0x02050f73, 0x0b132b33;
overlay "overlay": 0x060a18c8, 0x0b1330b0;
border "border": 0x1b2750ff, 0xd3dceeff;
border_strong "border-strong": 0x2a3a6eff, 0xb9c6e2ff;
border_popup "border-popup": 0x3d5296ff, 0x9fb0d4ff;
accent "accent": 0x2d6bffff, 0x2458e6ff;
accent_hover "accent-hover": 0x4a82ffff, 0x3a6cf0ff;
accent_pressed "accent-pressed": 0x1f55d9ff, 0x1b47c0ff;
accent_soft "accent-soft": 0x18348aff, 0xd6e2ffff;
accent_soft_hover "accent-soft-hover": 0x1d3d9cff, 0xc8d8ffff;
accent_text "accent-text": 0x5c9dffff, 0x1d4fd6ff;
name_text "name-text": 0x45b9ffff, 0x0f6cc4ff;
on_accent "on-accent": 0xffffffff, 0xffffffff;
glow "glow": 0x3f7bff90, 0x2458e660;
live "live": 0xff2d55ff, 0xe0203fff;
live_soft "live-soft": 0x3a0f22ff, 0xffe0e6ff;
danger "danger": 0xff4d5eff, 0xd92c3cff;
danger_soft "danger-soft": 0x3b1020ff, 0xffe3e6ff;
success "success": 0x22d36bff, 0x16a557ff;
success_soft "success-soft": 0x0d3326ff, 0xd7f5e4ff;
warning "warning": 0xf5b301ff, 0xb77f00ff;
warning_soft "warning-soft": 0x3a2a06ff, 0xfff0c8ff;
idle "idle": 0xf5b301ff, 0xc98b00ff;
dnd "dnd": 0xff4d5eff, 0xd92c3cff;
offline "offline": 0x5f6d93ff, 0x8d99b5ff;
gold "gold": 0xffc233ff, 0xd99a00ff;
info "info": 0x3fb3ffff, 0x1180d6ff;
text "text": 0xeef2ffff, 0x0e1733ff;
text_secondary "text-secondary": 0xaeb9d8ff, 0x43506fff;
text_muted "text-muted": 0x6d7ca6ff, 0x6f7b98ff;
text_disabled "text-disabled": 0x46527aff, 0xa7b1c8ff;
icon "icon": 0xb9c4e2ff, 0x43506fff;
meter_low "meter-low": 0x21d07aff, 0x21d07aff;
meter_mid "meter-mid": 0xf5d000ff, 0xf5d000ff;
meter_high "meter-high": 0xff4d5eff, 0xff4d5eff;
meter_off "meter-off": 0x1a2550ff, 0xd5ddefff;
}
/// `@linear-gradient(angle, stop 0%, stop 55%, stop 100%)`: the window's
/// backdrop. GPUI's `Background` has two colour stops, so what it draws
/// (`Backdrop::to_gpui`, in the theme module) is the first and the last; the
/// middle one stays here for a front end that can use it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Backdrop {
/// The direction in degrees, as CSS and Slint take it (0 is to the top).
pub angle: f32,
/// Three stops: colour and position (0 to 1).
pub stops: [(Rgba, f32); 3],
}
impl Backdrop {
/// The dark backdrop.
pub const DARK: Self = Self {
angle: 160.0,
stops: [(Rgba(0x0a1230ff), 0.0), (Rgba(0x060a18ff), 0.55), (Rgba(0x0a1638ff), 1.0)],
};
/// The light backdrop.
pub const LIGHT: Self = Self {
angle: 160.0,
stops: [(Rgba(0xf4f7fdff), 0.0), (Rgba(0xe6ecf8ff), 0.60), (Rgba(0xdde6f7ff), 1.0)],
};
}
/// The family of the UI font (`font-family` of `theme.slint`).
pub const FONT_FAMILY: &str = "Inter";
/// Every size, radius, weight and duration token of `theme.slint` for one
/// text size factor: lengths in logical pixels.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Metrics {
/// `font-scale`: multiplies every type size and the sizes that follow text.
pub font_scale: f32,
/// `radius-xs`.
pub radius_xs: f32,
/// `radius-sm`.
pub radius_sm: f32,
/// `radius-md`.
pub radius_md: f32,
/// `radius-lg`.
pub radius_lg: f32,
/// `radius-xl`.
pub radius_xl: f32,
/// `radius-pill`.
pub radius_pill: f32,
/// `space-1`.
pub space_1: f32,
/// `space-2`.
pub space_2: f32,
/// `space-3`.
pub space_3: f32,
/// `space-4`.
pub space_4: f32,
/// `space-5`.
pub space_5: f32,
/// `space-6`.
pub space_6: f32,
/// `space-7`.
pub space_7: f32,
/// `space-8`.
pub space_8: f32,
/// `font-xs` (scaled).
pub font_xs: f32,
/// `font-sm` (scaled).
pub font_sm: f32,
/// `font-body` (scaled).
pub font_body: f32,
/// `font-md` (scaled).
pub font_md: f32,
/// `font-lg` (scaled).
pub font_lg: f32,
/// `font-xl` (scaled).
pub font_xl: f32,
/// `font-2xl` (scaled).
pub font_2xl: f32,
/// `font-3xl` (scaled).
pub font_3xl: f32,
/// `weight-regular`.
pub weight_regular: u16,
/// `weight-medium`.
pub weight_medium: u16,
/// `weight-semibold`.
pub weight_semibold: u16,
/// `weight-bold`.
pub weight_bold: u16,
/// `row-height` (scaled).
pub row_height: f32,
/// `control-height` (scaled).
pub control_height: f32,
/// `control-height-sm` (scaled).
pub control_height_sm: f32,
/// `icon-sm`.
pub icon_sm: f32,
/// `icon-md`.
pub icon_md: f32,
/// `icon-lg`.
pub icon_lg: f32,
/// `glow-width`: the ring around focused and selected items.
pub glow_width: f32,
/// `rail-width`.
pub rail_width: f32,
/// `sidebar-width`: 264 and more with large text.
pub sidebar_width: f32,
/// `topbar-height`: 44, taller when large text makes the controls taller.
pub topbar_height: f32,
/// `right-panel-min`.
pub right_panel_min: f32,
/// `fast`, in milliseconds.
pub fast_ms: u32,
/// `normal`, in milliseconds.
pub normal_ms: u32,
}
impl Metrics {
/// The tokens at a text size factor (1 is the default).
pub fn new(font_scale: f32) -> Self {
let s = font_scale;
let control_height = 36.0 * s;
let space_3 = 8.0;
Self {
font_scale,
radius_xs: 4.0,
radius_sm: 6.0,
radius_md: 8.0,
radius_lg: 12.0,
radius_xl: 16.0,
radius_pill: 999.0,
space_1: 2.0,
space_2: 4.0,
space_3,
space_4: 12.0,
space_5: 16.0,
space_6: 20.0,
space_7: 24.0,
space_8: 32.0,
font_xs: 11.0 * s,
font_sm: 12.0 * s,
font_body: 14.0 * s,
font_md: 15.0 * s,
font_lg: 17.0 * s,
font_xl: 20.0 * s,
font_2xl: 24.0 * s,
font_3xl: 30.0 * s,
weight_regular: 400,
weight_medium: 500,
weight_semibold: 600,
weight_bold: 700,
row_height: 32.0 * s,
control_height,
control_height_sm: 28.0 * s,
icon_sm: 16.0,
icon_md: 20.0,
icon_lg: 24.0,
glow_width: 2.0,
rail_width: 72.0,
sidebar_width: 264.0 * s.max(1.0),
topbar_height: 44.0_f32.max(control_height + space_3),
right_panel_min: 220.0,
fast_ms: 120,
normal_ms: 200,
}
}
/// Every number token by the name it has in `theme.slint`, in its order:
/// lengths in pixels, weights as they are, durations in milliseconds.
pub fn entries(&self) -> Vec<(&'static str, f64)> {
let m = self;
[
("radius-xs", m.radius_xs),
("radius-sm", m.radius_sm),
("radius-md", m.radius_md),
("radius-lg", m.radius_lg),
("radius-xl", m.radius_xl),
("radius-pill", m.radius_pill),
("space-1", m.space_1),
("space-2", m.space_2),
("space-3", m.space_3),
("space-4", m.space_4),
("space-5", m.space_5),
("space-6", m.space_6),
("space-7", m.space_7),
("space-8", m.space_8),
("font-xs", m.font_xs),
("font-sm", m.font_sm),
("font-body", m.font_body),
("font-md", m.font_md),
("font-lg", m.font_lg),
("font-xl", m.font_xl),
("font-2xl", m.font_2xl),
("font-3xl", m.font_3xl),
("row-height", m.row_height),
("control-height", m.control_height),
("control-height-sm", m.control_height_sm),
("icon-sm", m.icon_sm),
("icon-md", m.icon_md),
("icon-lg", m.icon_lg),
("glow-width", m.glow_width),
("rail-width", m.rail_width),
("sidebar-width", m.sidebar_width),
("topbar-height", m.topbar_height),
("right-panel-min", m.right_panel_min),
]
.into_iter()
.map(|(name, value)| (name, f64::from(value)))
.chain([
("weight-regular", f64::from(m.weight_regular)),
("weight-medium", f64::from(m.weight_medium)),
("weight-semibold", f64::from(m.weight_semibold)),
("weight-bold", f64::from(m.weight_bold)),
("fast", f64::from(m.fast_ms)),
("normal", f64::from(m.normal_ms)),
])
.collect()
}
}
impl Default for Metrics {
fn default() -> Self {
Self::new(1.0)
}
}
+92
View File
@@ -0,0 +1,92 @@
//! The window's content. The shell is not built yet (slice 1 of the
//! migration): the window is the theme's page with the one line of the root
//! state that proves the loops run in a status bar, or, with
//! `VOELIN_OPEN=swatch`, the swatch page above that bar.
use gpui_kit::{
Context, Entity, IntoElement, ParentElement as _, Render, Styled as _, Window, div, px,
};
use crate::app::AppState;
use crate::dev::Page;
use crate::meter::Counters;
use crate::swatch::swatch;
use crate::theme::{VoelinTheme, hsla};
/// What the main window draws, from the root state and the theme.
pub struct MainView {
app: Entity<AppState>,
page: Page,
counters: Counters,
}
impl MainView {
/// A view of `app` that draws again whenever it changes, and that keeps
/// the theme in `system` mode in step with the window's appearance.
pub fn new(
app: Entity<AppState>,
page: Page,
counters: Counters,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
cx.observe(&app, |_, _, cx| cx.notify()).detach();
cx.observe_window_appearance(window, |_, window, cx| {
VoelinTheme::set_system_appearance(cx, window.appearance());
})
.detach();
Self { app, page, counters }
}
}
impl Render for MainView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.counters.renders.incr();
let line = self.app.read(cx).state_line();
let theme = VoelinTheme::global(cx).clone();
let (c, m) = (&theme.colors, &theme.metrics);
let page = match self.page {
Page::Swatch => div().flex_1().overflow_hidden().child(swatch(&theme)),
Page::Shell => div()
.flex_1()
.flex()
.flex_col()
.items_center()
.justify_center()
.gap(px(m.space_3))
.child(
div()
.text_size(px(m.font_3xl))
.text_color(hsla(c.text))
.child(voelin_platform::APP_NAME),
)
.child(
div()
.text_size(px(m.font_body))
.text_color(hsla(c.text_muted))
.child("The desktop shell is the next slice."),
),
};
div()
.size_full()
.flex()
.flex_col()
.bg(hsla(c.bg_app))
.text_color(hsla(c.text))
.font_family(crate::theme::FONT_FAMILY)
.child(page)
.child(
div()
.h(px(m.control_height_sm))
.px(px(m.space_5))
.flex()
.items_center()
.bg(hsla(c.surface))
.border_t_1()
.border_color(hsla(c.border))
.text_size(px(m.font_sm))
.text_color(hsla(c.text_secondary))
.child(line),
)
}
}
+154
View File
@@ -0,0 +1,154 @@
//! The binary's failure path, end to end: when the main window cannot be
//! opened (no display server, no Vulkan or GL driver), `voelin-gpui` prints
//! why and exits with status 1 instead of staying alive with no window and no
//! message.
//!
//! It has to start the real binary. GPUI's Linux platform runs the launch
//! callback before it starts its event loop, and the loop forgets a quit asked
//! for before it started, so a failure handled by quitting inside the
//! callback hung the process; the test platform of the unit tests has no such
//! loop and cannot show it.
//!
//! The no-driver test needs a test X server in `VOELIN_X11_TEST_DISPLAY` (an
//! Xvfb, as CI has; never the desktop's display) and is skipped without one.
#![cfg(target_os = "linux")]
use std::fs;
use std::os::unix::fs::PermissionsExt as _;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use std::time::{Duration, Instant};
/// Where the drivers are not: the Vulkan loader, EGL's vendor library
/// directory and Mesa's driver directory all point here.
const NOWHERE: &str = "/nonexistent-voelin-gpui-test";
/// Loaded machines are slow, so the wait is generous; a run that works takes a
/// second or two.
const WAIT: Duration = Duration::from_secs(120);
/// The scratch directory of one run, removed at the end.
struct Scratch(PathBuf);
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// How a run of the binary went.
enum Outcome {
/// It ended, with this status and this much of the log.
Ended(ExitStatus, String),
/// It picked a GPU: the window can open, so nothing failed.
Opened,
/// It was still running after [`WAIT`] with no GPU picked.
Hung(String),
}
/// Run the binary with the drivers hidden (`hide_drivers`) on `display`
/// (none: no display server at all) and wait for it to end, to pick a GPU or
/// to run out of time. Nothing of the user's state, display or session bus is
/// in its environment.
fn run_binary(name: &str, display: Option<&str>, hide_drivers: bool) -> Outcome {
let scratch = Scratch(
Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("{name}-{}", std::process::id())),
);
let home = scratch.0.join("home");
let runtime = scratch.0.join("runtime");
fs::create_dir_all(&runtime).unwrap();
fs::set_permissions(&runtime, fs::Permissions::from_mode(0o700)).unwrap();
let log = scratch.0.join("stderr.log");
let mut command = Command::new(env!("CARGO_BIN_EXE_voelin-gpui"));
command
.env_remove("DISPLAY")
.env_remove("WAYLAND_DISPLAY")
.env_remove("WAYLAND_SOCKET")
.env_remove("XDG_SESSION_TYPE")
.env_remove("DBUS_SESSION_BUS_ADDRESS")
.env_remove("RUST_LOG")
.env("HOME", &home)
.env("XDG_RUNTIME_DIR", &runtime)
.env("XDG_CONFIG_HOME", home.join("config"))
.env("XDG_DATA_HOME", home.join("data"))
.env("XDG_STATE_HOME", home.join("state"))
.env("XDG_CACHE_HOME", home.join("cache"))
.env("VOELIN_DATA_DIR", home.join("voelin"))
// The log line that tells a GPU was picked.
.env("VOELIN_LOG", "warn,voelin_gpui=info,gpui_wgpu=info")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(fs::File::create(&log).unwrap());
if let Some(display) = display {
command.env("DISPLAY", display);
}
if hide_drivers {
command
.env("VK_DRIVER_FILES", format!("{NOWHERE}/vulkan.json"))
.env("VK_ICD_FILENAMES", format!("{NOWHERE}/vulkan.json"))
.env("__EGL_VENDOR_LIBRARY_DIRS", NOWHERE)
.env("__EGL_VENDOR_LIBRARY_FILENAMES", format!("{NOWHERE}/egl.json"))
.env("LIBGL_DRIVERS_PATH", NOWHERE);
}
let mut child = command.spawn().unwrap();
let deadline = Instant::now() + WAIT;
loop {
if let Some(status) = child.try_wait().unwrap() {
return Outcome::Ended(status, fs::read_to_string(&log).unwrap_or_default());
}
let seen = fs::read_to_string(&log).unwrap_or_default();
let outcome = if seen.contains("Selected GPU adapter") {
Outcome::Opened
} else if Instant::now() > deadline {
Outcome::Hung(seen)
} else {
std::thread::sleep(Duration::from_millis(50));
continue;
};
let _ = child.kill();
let _ = child.wait();
return outcome;
}
}
#[test]
fn a_window_that_cannot_open_for_want_of_a_driver_ends_the_binary_with_an_error() {
let Some(display) = std::env::var("VOELIN_X11_TEST_DISPLAY").ok().filter(|d| !d.is_empty())
else {
eprintln!("skipped: VOELIN_X11_TEST_DISPLAY is not set");
return;
};
match run_binary("no-driver", Some(&display), true) {
Outcome::Ended(status, seen) => {
assert_eq!(status.code(), Some(1), "{seen}");
assert!(seen.contains("cannot open the main window"), "{seen}");
}
Outcome::Opened => eprintln!(
"skipped: this machine's driver was found in spite of the environment, \
so the window can open"
),
Outcome::Hung(seen) => panic!(
"still running after {WAIT:?} with no window and no GPU: a quit asked for in the \
launch callback is lost\n{seen}"
),
}
}
#[test]
fn without_a_display_server_the_binary_ends_with_an_error() {
match run_binary("no-display", None, false) {
Outcome::Ended(status, seen) => {
assert_eq!(status.code(), Some(1), "{seen}");
assert!(seen.contains("cannot open the main window"), "{seen}");
assert!(seen.contains("no display"), "{seen}");
}
Outcome::Opened => panic!("a GPU was picked without a display server"),
Outcome::Hung(seen) => panic!(
"still running after {WAIT:?} with no window: GPUI's headless platform keeps \
the app alive\n{seen}"
),
}
}
+7 -1
View File
@@ -69,7 +69,13 @@ tracing = "0.1.44"
yuv = "0.8.19"
[target.'cfg(target_os = "linux")'.dependencies]
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "tokio"], optional = true }
# `async-io`, not `tokio`: GPUI's Linux backend enables ashpd's `async-io`, ashpd
# refuses both at once, and a front end holds the portals and GPUI in one binary.
# zbus then runs every connection on an I/O thread of its own, whichever thread
# builds it: no crate of the workspace turns zbus's `tokio` feature on (with it
# zbus would pick tokio for a connection made inside a tokio runtime, and ashpd
# shares one connection per process with every later caller).
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "async-io"], optional = true }
memmap2 = { version = "0.9.11", optional = true }
pipewire = { version = "0.10.1", optional = true }
rustix = { version = "1.1.5", features = ["event", "fs", "stdio"], optional = true }
+7 -7
View File
@@ -279,14 +279,14 @@ impl FrameSink for QueueSink {
pub fn forward(mut frames: FrameReceiver<VideoFrame>, mut sink: Box<dyn FrameSink>) -> Result<()> {
std::thread::Builder::new().name("voelin-capture-forward".into()).spawn(move || {
loop {
match frames.recv_timeout(Duration::from_millis(100)) {
Some(frame) => {
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
break;
}
let Some(frame) = frames.recv_timeout(Duration::from_millis(100)) else {
if frames.is_closed() {
break;
}
None if frames.is_closed() => break,
None => {}
continue;
};
if sink.wants(frame.timestamp) && !sink.frame(frame.view()) {
break;
}
}
})?;
+3 -1
View File
@@ -181,7 +181,9 @@ impl ScreenCapture for PortalCapture {
}
/// Asks the user through the portal dialog (unless a restore token
/// applies). Needs a tokio runtime (the D-Bus connection runs on it).
/// applies). Any executor will do: ashpd runs on zbus's `async-io` in every
/// binary of the workspace (no crate turns zbus's `tokio` feature on), whose
/// connection has an I/O thread of its own, whichever thread builds it.
fn start(
&mut self,
source: &SourceId,
+2 -2
View File
@@ -446,7 +446,7 @@ fn files_in(dir: &Path, base: &str) -> Vec<PathBuf> {
matches.then(|| (major_of(&name).unwrap_or(0), e.path()))
})
.collect();
found.sort_by(|a, b| b.0.cmp(&a.0));
found.sort_by_key(|entry| std::cmp::Reverse(entry.0));
found.into_iter().map(|(_, p)| p).collect()
}
@@ -466,7 +466,7 @@ fn ldconfig(base: &str) -> Vec<PathBuf> {
name.starts_with(&prefix).then(|| (major_of(name).unwrap_or(0), PathBuf::from(path)))
})
.collect();
found.sort_by(|a, b| b.0.cmp(&a.0));
found.sort_by_key(|entry| std::cmp::Reverse(entry.0));
found.into_iter().map(|(_, p)| p).collect()
}
+2 -2
View File
@@ -603,8 +603,8 @@ mod v4l2 {
// Seconds per frame; a stepwise range starts with its smallest
// interval, which is the highest rate.
let (num, den) = (entry.interval[0], entry.interval[1]);
if num > 0 {
best = best.max(den / num);
if let Some(rate) = den.checked_div(num) {
best = best.max(rate);
}
if entry.type_ != FRMIVAL_DISCRETE {
break;
+36 -19
View File
@@ -1180,19 +1180,32 @@ mod tests {
scenes
}
/// The first preview frame that `wanted` takes. The preview keeps the latest
/// frame only, so few older ones are waiting or on their way: the number of
/// frames looked at is the bound (the work), and the wait for each, which a
/// busy machine can stretch, only ends a hang.
fn preview_until(
preview: &Handoff<VideoFrame>,
wanted: impl Fn(&VideoFrame) -> bool,
) -> Arc<VideoFrame> {
for _ in 0..20 {
let frame = preview.wait_timeout(Duration::from_secs(30)).expect("a preview frame");
if wanted(&frame) {
return frame;
}
}
panic!("the preview never showed what was asked for");
}
#[tokio::test]
async fn it_composes_into_the_preview_and_follows_commands() {
let studio = Studio::start(one_colour_scene()).await.unwrap();
let preview = studio.preview();
studio.apply(Command::SetPreview { width: 32, height: 24, fps: 60 }).await.unwrap();
let started = Instant::now();
let frame = loop {
if let Some(frame) = preview.wait_timeout(Duration::from_millis(200)) {
break frame;
}
assert!(started.elapsed() < Duration::from_secs(5), "no preview frame");
};
assert_eq!((frame.width, frame.height), (32, 24));
// The studio composes from the moment it starts, at the size and rate the
// preview has then (480x270, 15 fps): a frame of that size can be the
// first one there is.
let frame = preview_until(&preview, |f| (f.width, f.height) == (32, 24));
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!("not RGBA") };
assert_eq!(&p.data[..4], &[9, 8, 7, 255]);
@@ -1211,15 +1224,12 @@ mod tests {
.unwrap();
studio.apply(Command::SetActiveScene { scene: break_id }).await.unwrap();
assert_eq!(studio.status().active_scene, break_id);
// The new scene's source draws.
let frame = loop {
let frame = preview.wait_timeout(Duration::from_secs(2)).expect("a preview frame");
let crate::frame::FrameData::Rgba(p) = &frame.data else { panic!() };
if p.data[..3] == [1, 2, 3] {
break frame;
}
assert!(started.elapsed() < Duration::from_secs(10), "the scene never switched");
};
// The new scene's source draws, from the first frame composed after the
// command.
let frame = preview_until(
&preview,
|f| matches!(&f.data, crate::frame::FrameData::Rgba(p) if p.data[..3] == [1, 2, 3]),
);
drop(frame);
studio.apply(Command::RemoveScene { scene: break_id }).await.unwrap();
@@ -1402,9 +1412,16 @@ mod tests {
assert_eq!((listed[0].width, listed[0].height), (64, 48));
let frames = capture.start(&SourceId::Studio, &CaptureOptions::default()).await.unwrap();
let mut frames = frames;
let frame = frames.recv_timeout(Duration::from_secs(5)).expect("a composed frame");
// (The wait only ends a hang.)
let frame = frames.recv_timeout(Duration::from_secs(30)).expect("a composed frame");
assert_eq!((frame.width, frame.height), (64, 48));
assert!(studio.shared.delivered.load(Ordering::Relaxed) > 0);
// A frame is counted once it has been handed over, so the count can still be
// behind when the frame is in the hands of the test.
let deadline = Instant::now() + Duration::from_secs(30);
while studio.shared.delivered.load(Ordering::Relaxed) == 0 {
assert!(Instant::now() < deadline, "the frame handed over was never counted");
std::thread::sleep(Duration::from_millis(5));
}
capture.stop();
std::fs::remove_dir_all(&dir).ok();
}
@@ -350,7 +350,22 @@ mod tests {
#[test]
fn an_unwritable_path_fails_at_once() {
assert!(Recorder::start("/nonexistent-root-dir/x/clip.webm", 0, 2).is_err());
assert!(Recorder::start("clip.mp4", 0, 2).is_err());
let dir = dir("unwritable");
// A path below a regular file fails for every user, root included
// (ENOTDIR). A directory that is merely missing would be created, and
// a read-only one is written to by root.
let file = dir.join("not-a-directory");
std::fs::write(&file, b"x").unwrap();
assert!(Recorder::start(file.join("x").join("clip.webm"), 0, 2).is_err());
// The directory is there and the file cannot be created because the
// path names a directory (EISDIR, again for every user).
let named_like_a_file = dir.join("clip.webm");
std::fs::create_dir(&named_like_a_file).unwrap();
assert!(Recorder::start(&named_like_a_file, 0, 2).is_err());
// A name that asks for no known container is refused before any file
// is created.
assert!(Recorder::start(dir.join("clip.mp4"), 0, 2).is_err());
assert!(!dir.join("clip.mp4").exists());
std::fs::remove_dir_all(&dir).ok();
}
}
-18
View File
@@ -1,18 +0,0 @@
[package]
name = "voelin-model"
version = "0.1.0"
description = "UI-facing domain model shared by the client engine, gateway and UI (no IO)."
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
publish.workspace = true
[dependencies]
serde = { version = "1", features = ["derive"] }
[dev-dependencies]
serde_json = "1"
[lints]
workspace = true
-94
View File
@@ -1,94 +0,0 @@
uid,name,description,filename,codes
4b27be5a-b92a-4b30-8b2d-14b59653f427,20th Anniversary,Celebrating 20 Years of TeamSpeak,20_years,
f81ad44d-e931-47d1-a3ef-5fd160217cf8,4Netplayers,4Netplayers customer,4netplayers,
b78a0f3e-8758-4572-b102-42a79b4a0342,????,Reads between the line,hat,
2bf80270-8efe-46dc-a472-3280a0479145,Alpha Tester,Helped to test our software. THANK YOU!,Alpha,
05114019-6b46-4b13-b5a1-e5179ef69fb5,April Fools!,"Roses are red, gaming is fun, you are carrying too much to be able to run :(",rpg,
1a518885-520c-4f54-9f49-8b1acb674771,Braindance,I’m chippin’ in,Braindance,P4TEKZ80PZ
cbf5aafd-2554-4053-80bb-0cf82ec0a430,Bright Idea,TeamSpeak took my idea on board,FeatureBadge_Lightbulb,
d6062d9c-42a3-49c9-91dd-8c43a5a46805,Bug Catcher,I found a bug!,BugBadge_Splat,
dfc70674-0fd0-431e-b3a1-edc32d7b09b2,Challenge Accepted,"Unlocked at SCILL Play — Challenges, tournaments and more!",scill,
afed63f4-82f1-4479-ab02-0ef053f55723,Communities Early Adopter,Thank you for your Support!,communities_early_adopter,
54be472d-3163-4076-9059-7f46128d937e,Communities Purchase,Purchased a TeamSpeak Community,communities_purchase,
f85f7e21-753a-4566-b26a-4e3e9155d2ef,Cyberpunk,We have a city to burn,Cyberpunk,
c028298c-84ff-4e22-be4e-b8c17552b4bb,Digi,Digi joined your channel #DIGWIN,digi,
56df5ce2-6c5a-4a24-90e2-29e497e26170,Drone Champions League,I follow the Drone Champions League,DCL_Badge,DRONECHAMP
935e5a2a-954a-44ca-aa7a-55c79285b601,E3 2018 - Winner,Discovered at E3 2018,E3-2018,
61723e54-3da2-4f19-a33f-fcdc8ef5eaa0,Father's Day 2022,Not all heroes wear capes,fathersday2022,
b9c7d6ad-5b99-40fb-988c-1d02ab6cc130,Found Tim Speak,Found Tim Speak at Gamescom 2018,met_tim,XJN4WJZEJN
809bdd5a-2601-4152-82ff-a21d23d8fd46,G2 Esports,Aged 20 years being a G2 fan,G2_Esports,
62444179-0d99-42ba-a45c-c6b1557d079a,Gamescom 2014,Registered at Gamescom 2014,gamescom_2014,
50bbdbc8-0f2a-46eb-9808-602225b49627,Gamescom 2016,Registered during Gamescom 2016,gamescom_2016,
534c9582-ab02-4267-aec6-2d94361daa2a,Gamescom 2017,Visited TeamSpeak at Gamescom 2017,gamescom_2017,DK9JGRJH1Q
4eef1ecf-a0ea-423d-bfd0-496543a00305,Gamescom 2018,Visited TeamSpeak at Gamescom 2018,gamescom_2018,8CXB49KPJ4
b82a45a5-b235-4926-be77-de102222e5eb,Gamescom 2019,Visited TeamSpeak at Gamescom 2019,Gamescom19,PNKCB76VZ8
34dbfa8f-bd27-494c-aa08-a312fc0bb240,Gamescom Hero 2017,Gaming Hero at Gamescom 2017,hero_2017,
24512806-f886-4440-b579-9e26e4219ef6,Gamescom Hero 2018,Gamescom Exclusive Gaming Hero 2018,gamescom_2018_played,BJCFQBU53C
d49fd07e-99fb-41de-8d7b-c98064713171,GommeHD.net,Your #1 Minecraft Network for over 10 years,GMHD,
c565972a-3912-457b-826f-84820c1ba6ca,Halloween 2021,Happy Halloween 2021,halloween21,
133595e7-950f-4ef2-b113-f91a68b5770d,Halloween 2021 Special,Earned by participating in our Halloween 2021 special stream,halloween21_special,
fb154277-5fe7-428a-85a4-43c0bdcdda3d,Halloween 2022,Spooky_Scary_Skeletons.mp4,halloween22,
e6679ce2-d458-493c-8ffb-5660e47ac99f,Happy Hanami,Enjoy the view,hanami2023,
de7bd960-eb02-47e1-9ce2-a44f6e255d8f,Happy Holidays 2019,Happy holidays from everyone at TeamSpeak!,Happy_Holidays,
d4ea0251-ba46-4c1a-83b7-59db3f89e52c,Happy New Year 2021,Survived the great toilet paper crisis of 2020,firework_2020,
1519e001-06a0-458c-9195-a8a6d0ec87fc,Happy New Year 2023,"Aw man, here we go again",2023_NewYear,
834d4cc1-cd80-48d6-96c4-23d131d78649,Happy Summer 2023,heat death of the universe,happy_summer_2023,
c68bcc52-7aeb-4868-b4d2-e7b20716f9ba,Heatwave 2022,I'm melting... help,summer_icecream,
94242c4e-6742-4540-8b66-ce951ed57159,Helping Hand,\ pushed some buttons *beep* *bop* ~ thanks!,homebase,
288a56c6-4da3-48de-9c9f-bd9eede5d832,Immortal Roleplay,This is your life.,Immortal_Roleplay,
69bfffc8-e9c0-4f70-8a37-47cb8c73fb1d,International Peace Day,"United we stand, divided we fall",peaceday2022,
9ea23c77-8755-4d82-b30c-92f4aac109ef,International Women's Day 2021,"To all the mums, sisters, aunties, nieces and beyond, Happy Women's Day!",wft,
7d9fa2b1-b6fa-47ad-9838-c239a4ddd116,MIFCOM,MIFCOM | Entered Performance,mifcom,
ed85bdff-2a2b-4bea-a1a5-4d06fcc0d776,Merry Christmas 2019,It’s the most wonderful ‘Tim’ of the Year,Christmas,
c6480fe2-ee25-4ee8-9853-243652c8ec54,Merry Christmas 2020,"Let it snow, let it snow, let it snow!",Christmas2020,
0581aa0f-8c2d-4681-bb9f-8492fec49977,Merry Christmas 2021,Look what Santa's left under the server tree!,christmas2021,
d4875b30-9908-43cb-a1eb-1a958e226078,Merry Christmas 2022,There's snow place like home,christmas2022,
87ccf9ea-67c9-45e5-adbc-77e210e6128a,Met Tim,Met Tim Speak IRL,tim_irl,
0d98391c-ecdf-4f26-931a-49bfd669cda7,Mind Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_MindEgg,
2fdda3c6-20e0-48f1-9c12-f39239a2ed02,Mother's Day 2022,Thanks for bearing with us,rose,
c3f823eb-5d5c-40f9-9dbd-3437d59a539d,Official TeamSpeak Gamer,New myTeamSpeak member,TS-2018,
8dfa37ac-b40d-4466-b393-ff2184a9adf3,Overwatch League,I follow the Overwatch League,OWL_Badge,
4ce435d1-6ac5-4530-b81d-6d14ddaaa1ac,PGL Antwerp 2022,Watched the PGL CS:GO Major,PGLant,
fa3ece28-64df-431f-b1b3-90844bfdd2d9,Paris Games Week 2014,Registered at Paris Games Week 2014,paris_gamesweek_2014,
d95f9901-c42d-4bac-8849-7164fd9e2310,Paris Games Week 2016,Registered during Paris Games Week 2016,paris_gamesweek_2016,
0005232e-538e-4cb2-93b6-d7d83e873829,PietSmiet,Werde Snob auf PietSmiet.de ;),PietSmiet,
be932556-dfa9-4dc6-afd0-98de0ab25777,PolTeamgeist,WooOOHoohOOHooo,PolTeamgeist,
5f6d49e4-35c8-4809-8c81-6e71f7f749e9,Power Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_PowerEgg,
ceee2445-4fbf-4f06-9421-286f0f4e875a,Pride,Never be afraid to show your colors.,pride,
1aa375e8-7207-45bf-8b80-556bafafc834,Reality Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_RealityEgg,
f22c22f1-8e2d-4d99-8de9-f352dc26ac5b,Rocket Beans TV,Rocket Beans TV Community,rbtv,RWGE2NURJZ
2c9698c1-1fec-4baa-a28f-4845f045f42f,Soul Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SoulEgg,
641a4d85-2351-482c-97a1-02fc3b6abbb5,Space Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_SpaceEgg,
63261116-4359-4842-873e-56820afbe068,SpartaTheOriginal,Olaf Toast @ twitch.tv/SpartaTheOriginal,Toast,
ef567ec5-f46e-4520-be07-6021023cf6bd,Sponsorship License,Sponsored by TeamSpeak,Sponsorship,
7a627d47-5496-4d68-83b5-2c4eafff9b30,"Stay Home, Stay Safe","Playing Apart, Staying Connected",StaySafeStayHome,
7262a528-c7df-4369-bc2c-d34bf5853d7b,TS Chat Alpha Tester,"Helped us test our new mobile app, thanks!",slim_golden,
6eee759e-b1e9-4937-b023-07fc778532a2,TS Gameday Participant,At least i tried...,silvered,
e1447b99-53b0-448a-98b7-ee7bad8bd268,TS Gameday Winner,As shiny as the golden frying pan,goldenjoystick,
1cb07348-34a4-4741-b50f-c41e584370f7,TeamSpeak Addon Author,Creator of TeamSpeak Addons,addon_author,
450f81c1-ab41-4211-a338-222fa94ed157,TeamSpeak Addon Developer (Bronze),Creator of at least 1 TeamSpeak Addon,addon_author_bronze,
94ec66de-5940-4e38-b002-970df0cf6c94,TeamSpeak Addon Developer (Gold),Creator of at least 5 TeamSpeak Addons,addon_author_gold,
c9e97536-5a2d-4c8e-a135-af404587a472,TeamSpeak Addon Developer (Silver),Creator of at least 3 TeamSpeak Addons,addon_author_silver,
9cd152a7-bf65-4ece-aeba-62d27678f79a,TeamSpeak Competition Winner Badge,TeamSpeak Competition Winner,CompWinnerBadge,
64221fd1-706c-4bb2-ba55-996c39effa79,TeamSpeak Jedi,myTeamSpeak early adopter,TS-OG,
6b187e83-873b-46b0-b2c2-a31af15e76a4,TeamSpeak Merch Badge,TeamSpeak Merch Owner - 1st Edition,cap_red,
22b9ec39-7694-453e-864c-dfc7b1b0d7c7,TeamSpeak Merch Badge 2.0,TeamSpeak Merch Owner - 2nd Edition,topper,
205916f3-a953-4754-8905-bc15069b1f91,TeamSpeak Merch Badge 3.0,TeamSpeak Merch Owner — 3rd Edition,Merch3,
8d843dfa-c51a-407f-87b3-94cfc8f03e96,TeamSpeak Staff,Official Staff Member,teamspeak_staff,
c2368518-3728-4260-bcd1-8b85e9f8984c,Test,"Testing, Testing.",Testing,
4086a249-a503-4f31-9e83-8a0a8e3089bd,Tim-o'-Lantern,Mwuhaahaahaahaahaa,Tim-O-Lantern,JQGCTAQWHT
089c7295-3aa2-48b0-b2f1-2dd1bec12caf,Time Egg,Found in the TeamSpeak 2020 Easter Egg Hunt,E_TimeEgg,
904e232c-f369-44db-87f7-5142e15620cc,Time Machine,Worked like a machine to update addons in super-quick time.,time_machine,
4c61af66-22ef-4897-b0bb-25fcef2acf60,Undead Nightmare,I'm the last of my kind,undead_nightmare,
b0a36aea-3e46-4e83-a455-6e92ae1b9d94,Undead Nightmare,I'm the last of my kind,undead_nightmare,
0cd924ed-c5ea-459e-b60a-4f1bc0b65f07,"Up, Up and Away!",Find me on Mount Chiliad,"up,_up_and_away!",
4b0fd4f5-d456-4294-973d-853a1db5c7d8,Valentim's Day 2019,Valentim's Day 2019,Valentines_Badge,
92801833-e721-4b7e-84d4-6c02dbb332b9,Valentim's Day 2020,Valentim's Day 2020,Valentim2020,
958f904b-8260-48a4-a961-f786cbd39411,Valentine's Day 2023,Love you like my Tamagotchi,ValentinesDay23,
a676c708-da67-4784-ba7f-3fb7e8d2e865,Valentines Day 2021,"Roses are red, TS is blue, Servers are Sweet and so are you.",valentine21,
c54a9f92-07f7-4214-90f3-eafeea8005da,World Backup Day,Don't be an April Fool. Back up your data!,backupday_2023,
448a6d13-4e08-46a1-aafa-b4ff6d6c2d06,World Bonsai Day,"harmony, balance, patience",bonsai_day,
0f976a27-ddf5-447c-b79c-0644a8e8a297,Year of the Dragon 2024,"Arise, Shenron!",year_of_the_dragon_2024,
8c22fe26-30ac-4231-8b31-67d8a75c808a,Year of the Ox 2021,Only listen to the fortune cookie; disregard all other fortune telling units.,ox21,
970c70e6-00a1-41c1-ac5c-81c89a06c7a6,Year of the Rabbit 2023,Do a barrel roll!,chineseNY2023,
92356386-0451-4a97-87d9-10ff4f43260c,Year of the Tiger 2022,Rocky sends his regards,tiger,
1 uid name description filename codes
2 4b27be5a-b92a-4b30-8b2d-14b59653f427 20th Anniversary Celebrating 20 Years of TeamSpeak 20_years
3 f81ad44d-e931-47d1-a3ef-5fd160217cf8 4Netplayers 4Netplayers customer 4netplayers
4 b78a0f3e-8758-4572-b102-42a79b4a0342 ???? Reads between the line hat
5 2bf80270-8efe-46dc-a472-3280a0479145 Alpha Tester Helped to test our software. THANK YOU! Alpha
6 05114019-6b46-4b13-b5a1-e5179ef69fb5 April Fools! Roses are red, gaming is fun, you are carrying too much to be able to run :( rpg
7 1a518885-520c-4f54-9f49-8b1acb674771 Braindance I’m chippin’ in Braindance P4TEKZ80PZ
8 cbf5aafd-2554-4053-80bb-0cf82ec0a430 Bright Idea TeamSpeak took my idea on board FeatureBadge_Lightbulb
9 d6062d9c-42a3-49c9-91dd-8c43a5a46805 Bug Catcher I found a bug! BugBadge_Splat
10 dfc70674-0fd0-431e-b3a1-edc32d7b09b2 Challenge Accepted Unlocked at SCILL Play — Challenges, tournaments and more! scill
11 afed63f4-82f1-4479-ab02-0ef053f55723 Communities Early Adopter Thank you for your Support! communities_early_adopter
12 54be472d-3163-4076-9059-7f46128d937e Communities Purchase Purchased a TeamSpeak Community communities_purchase
13 f85f7e21-753a-4566-b26a-4e3e9155d2ef Cyberpunk We have a city to burn Cyberpunk
14 c028298c-84ff-4e22-be4e-b8c17552b4bb Digi Digi joined your channel #DIGWIN digi
15 56df5ce2-6c5a-4a24-90e2-29e497e26170 Drone Champions League I follow the Drone Champions League DCL_Badge DRONECHAMP
16 935e5a2a-954a-44ca-aa7a-55c79285b601 E3 2018 - Winner Discovered at E3 2018 E3-2018
17 61723e54-3da2-4f19-a33f-fcdc8ef5eaa0 Father's Day 2022 Not all heroes wear capes fathersday2022
18 b9c7d6ad-5b99-40fb-988c-1d02ab6cc130 Found Tim Speak Found Tim Speak at Gamescom 2018 met_tim XJN4WJZEJN
19 809bdd5a-2601-4152-82ff-a21d23d8fd46 G2 Esports Aged 20 years being a G2 fan G2_Esports
20 62444179-0d99-42ba-a45c-c6b1557d079a Gamescom 2014 Registered at Gamescom 2014 gamescom_2014
21 50bbdbc8-0f2a-46eb-9808-602225b49627 Gamescom 2016 Registered during Gamescom 2016 gamescom_2016
22 534c9582-ab02-4267-aec6-2d94361daa2a Gamescom 2017 Visited TeamSpeak at Gamescom 2017 gamescom_2017 DK9JGRJH1Q
23 4eef1ecf-a0ea-423d-bfd0-496543a00305 Gamescom 2018 Visited TeamSpeak at Gamescom 2018 gamescom_2018 8CXB49KPJ4
24 b82a45a5-b235-4926-be77-de102222e5eb Gamescom 2019 Visited TeamSpeak at Gamescom 2019 Gamescom19 PNKCB76VZ8
25 34dbfa8f-bd27-494c-aa08-a312fc0bb240 Gamescom Hero 2017 Gaming Hero at Gamescom 2017 hero_2017
26 24512806-f886-4440-b579-9e26e4219ef6 Gamescom Hero 2018 Gamescom Exclusive Gaming Hero 2018 gamescom_2018_played BJCFQBU53C
27 d49fd07e-99fb-41de-8d7b-c98064713171 GommeHD.net Your #1 Minecraft Network for over 10 years GMHD
28 c565972a-3912-457b-826f-84820c1ba6ca Halloween 2021 Happy Halloween 2021 halloween21
29 133595e7-950f-4ef2-b113-f91a68b5770d Halloween 2021 Special Earned by participating in our Halloween 2021 special stream halloween21_special
30 fb154277-5fe7-428a-85a4-43c0bdcdda3d Halloween 2022 Spooky_Scary_Skeletons.mp4 halloween22
31 e6679ce2-d458-493c-8ffb-5660e47ac99f Happy Hanami Enjoy the view hanami2023
32 de7bd960-eb02-47e1-9ce2-a44f6e255d8f Happy Holidays 2019 Happy holidays from everyone at TeamSpeak! Happy_Holidays
33 d4ea0251-ba46-4c1a-83b7-59db3f89e52c Happy New Year 2021 Survived the great toilet paper crisis of 2020 firework_2020
34 1519e001-06a0-458c-9195-a8a6d0ec87fc Happy New Year 2023 Aw man, here we go again 2023_NewYear
35 834d4cc1-cd80-48d6-96c4-23d131d78649 Happy Summer 2023 heat death of the universe happy_summer_2023
36 c68bcc52-7aeb-4868-b4d2-e7b20716f9ba Heatwave 2022 I'm melting... help summer_icecream
37 94242c4e-6742-4540-8b66-ce951ed57159 Helping Hand \ pushed some buttons *beep* *bop* ~ thanks! homebase
38 288a56c6-4da3-48de-9c9f-bd9eede5d832 Immortal Roleplay This is your life. Immortal_Roleplay
39 69bfffc8-e9c0-4f70-8a37-47cb8c73fb1d International Peace Day United we stand, divided we fall peaceday2022
40 9ea23c77-8755-4d82-b30c-92f4aac109ef International Women's Day 2021 To all the mums, sisters, aunties, nieces and beyond, Happy Women's Day! wft
41 7d9fa2b1-b6fa-47ad-9838-c239a4ddd116 MIFCOM MIFCOM | Entered Performance mifcom
42 ed85bdff-2a2b-4bea-a1a5-4d06fcc0d776 Merry Christmas 2019 It’s the most wonderful ‘Tim’ of the Year Christmas
43 c6480fe2-ee25-4ee8-9853-243652c8ec54 Merry Christmas 2020 Let it snow, let it snow, let it snow! Christmas2020
44 0581aa0f-8c2d-4681-bb9f-8492fec49977 Merry Christmas 2021 Look what Santa's left under the server tree! christmas2021
45 d4875b30-9908-43cb-a1eb-1a958e226078 Merry Christmas 2022 There's snow place like home christmas2022
46 87ccf9ea-67c9-45e5-adbc-77e210e6128a Met Tim Met Tim Speak IRL tim_irl
47 0d98391c-ecdf-4f26-931a-49bfd669cda7 Mind Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_MindEgg
48 2fdda3c6-20e0-48f1-9c12-f39239a2ed02 Mother's Day 2022 Thanks for bearing with us rose
49 c3f823eb-5d5c-40f9-9dbd-3437d59a539d Official TeamSpeak Gamer New myTeamSpeak member TS-2018
50 8dfa37ac-b40d-4466-b393-ff2184a9adf3 Overwatch League I follow the Overwatch League OWL_Badge
51 4ce435d1-6ac5-4530-b81d-6d14ddaaa1ac PGL Antwerp 2022 Watched the PGL CS:GO Major PGLant
52 fa3ece28-64df-431f-b1b3-90844bfdd2d9 Paris Games Week 2014 Registered at Paris Games Week 2014 paris_gamesweek_2014
53 d95f9901-c42d-4bac-8849-7164fd9e2310 Paris Games Week 2016 Registered during Paris Games Week 2016 paris_gamesweek_2016
54 0005232e-538e-4cb2-93b6-d7d83e873829 PietSmiet Werde Snob auf PietSmiet.de ;) PietSmiet
55 be932556-dfa9-4dc6-afd0-98de0ab25777 PolTeamgeist WooOOHoohOOHooo PolTeamgeist
56 5f6d49e4-35c8-4809-8c81-6e71f7f749e9 Power Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_PowerEgg
57 ceee2445-4fbf-4f06-9421-286f0f4e875a Pride Never be afraid to show your colors. pride
58 1aa375e8-7207-45bf-8b80-556bafafc834 Reality Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_RealityEgg
59 f22c22f1-8e2d-4d99-8de9-f352dc26ac5b Rocket Beans TV Rocket Beans TV Community rbtv RWGE2NURJZ
60 2c9698c1-1fec-4baa-a28f-4845f045f42f Soul Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_SoulEgg
61 641a4d85-2351-482c-97a1-02fc3b6abbb5 Space Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_SpaceEgg
62 63261116-4359-4842-873e-56820afbe068 SpartaTheOriginal Olaf Toast @ twitch.tv/SpartaTheOriginal Toast
63 ef567ec5-f46e-4520-be07-6021023cf6bd Sponsorship License Sponsored by TeamSpeak Sponsorship
64 7a627d47-5496-4d68-83b5-2c4eafff9b30 Stay Home, Stay Safe Playing Apart, Staying Connected StaySafeStayHome
65 7262a528-c7df-4369-bc2c-d34bf5853d7b TS Chat Alpha Tester Helped us test our new mobile app, thanks! slim_golden
66 6eee759e-b1e9-4937-b023-07fc778532a2 TS Gameday Participant At least i tried... silvered
67 e1447b99-53b0-448a-98b7-ee7bad8bd268 TS Gameday Winner As shiny as the golden frying pan goldenjoystick
68 1cb07348-34a4-4741-b50f-c41e584370f7 TeamSpeak Addon Author Creator of TeamSpeak Addons addon_author
69 450f81c1-ab41-4211-a338-222fa94ed157 TeamSpeak Addon Developer (Bronze) Creator of at least 1 TeamSpeak Addon addon_author_bronze
70 94ec66de-5940-4e38-b002-970df0cf6c94 TeamSpeak Addon Developer (Gold) Creator of at least 5 TeamSpeak Addons addon_author_gold
71 c9e97536-5a2d-4c8e-a135-af404587a472 TeamSpeak Addon Developer (Silver) Creator of at least 3 TeamSpeak Addons addon_author_silver
72 9cd152a7-bf65-4ece-aeba-62d27678f79a TeamSpeak Competition Winner Badge TeamSpeak Competition Winner CompWinnerBadge
73 64221fd1-706c-4bb2-ba55-996c39effa79 TeamSpeak Jedi myTeamSpeak early adopter TS-OG
74 6b187e83-873b-46b0-b2c2-a31af15e76a4 TeamSpeak Merch Badge TeamSpeak Merch Owner - 1st Edition cap_red
75 22b9ec39-7694-453e-864c-dfc7b1b0d7c7 TeamSpeak Merch Badge 2.0 TeamSpeak Merch Owner - 2nd Edition topper
76 205916f3-a953-4754-8905-bc15069b1f91 TeamSpeak Merch Badge 3.0 TeamSpeak Merch Owner — 3rd Edition Merch3
77 8d843dfa-c51a-407f-87b3-94cfc8f03e96 TeamSpeak Staff Official Staff Member teamspeak_staff
78 c2368518-3728-4260-bcd1-8b85e9f8984c Test Testing, Testing. Testing
79 4086a249-a503-4f31-9e83-8a0a8e3089bd Tim-o'-Lantern Mwuhaahaahaahaahaa Tim-O-Lantern JQGCTAQWHT
80 089c7295-3aa2-48b0-b2f1-2dd1bec12caf Time Egg Found in the TeamSpeak 2020 Easter Egg Hunt E_TimeEgg
81 904e232c-f369-44db-87f7-5142e15620cc Time Machine Worked like a machine to update addons in super-quick time. time_machine
82 4c61af66-22ef-4897-b0bb-25fcef2acf60 Undead Nightmare I'm the last of my kind undead_nightmare
83 b0a36aea-3e46-4e83-a455-6e92ae1b9d94 Undead Nightmare I'm the last of my kind undead_nightmare
84 0cd924ed-c5ea-459e-b60a-4f1bc0b65f07 Up, Up and Away! Find me on Mount Chiliad up,_up_and_away!
85 4b0fd4f5-d456-4294-973d-853a1db5c7d8 Valentim's Day 2019 Valentim's Day 2019 Valentines_Badge
86 92801833-e721-4b7e-84d4-6c02dbb332b9 Valentim's Day 2020 Valentim's Day 2020 Valentim2020
87 958f904b-8260-48a4-a961-f786cbd39411 Valentine's Day 2023 Love you like my Tamagotchi ValentinesDay23
88 a676c708-da67-4784-ba7f-3fb7e8d2e865 Valentines Day 2021 Roses are red, TS is blue, Servers are Sweet and so are you. valentine21
89 c54a9f92-07f7-4214-90f3-eafeea8005da World Backup Day Don't be an April Fool. Back up your data! backupday_2023
90 448a6d13-4e08-46a1-aafa-b4ff6d6c2d06 World Bonsai Day harmony, balance, patience bonsai_day
91 0f976a27-ddf5-447c-b79c-0644a8e8a297 Year of the Dragon 2024 Arise, Shenron! year_of_the_dragon_2024
92 8c22fe26-30ac-4231-8b31-67d8a75c808a Year of the Ox 2021 Only listen to the fortune cookie; disregard all other fortune telling units. ox21
93 970c70e6-00a1-41c1-ac5c-81c89a06c7a6 Year of the Rabbit 2023 Do a barrel roll! chineseNY2023
94 92356386-0451-4a97-87d9-10ff4f43260c Year of the Tiger 2022 Rocky sends his regards tiger
-144
View File
@@ -1,144 +0,0 @@
//! myTeamSpeak badges: what the GUIDs a client shows (`client_badges`)
//! stand for, and where TeamSpeak keeps their pictures.
//!
//! The table is `data/badges.csv`: tsclientlib's list (2023, also in
//! `proto/tsproto-structs/declarations`) and the newer badges of
//! TeamSpeak's own list (`https://badges-content.teamspeak.com/list`, a
//! protobuf) as of October 2026. Badges added since are unknown here.
use std::collections::HashMap;
use std::sync::LazyLock;
/// How many badges a client shows at most (TeamSpeak lets one pick three).
pub const SHOWN: usize = 3;
/// TeamSpeak's server for the badges' pictures.
const CONTENT: &str = "https://badges-content.teamspeak.com";
/// One badge of the table.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BadgeInfo {
pub name: String,
pub description: String,
/// Its picture's name on TeamSpeak's server, without `.svg`.
pub filename: String,
}
/// The table by GUID (lower case), read once.
static BADGES: LazyLock<HashMap<String, BadgeInfo>> = LazyLock::new(|| {
// Columns: uid, name, description, filename, codes.
records(include_str!("../data/badges.csv"))
.into_iter()
.skip(1)
.filter_map(|mut fields| {
fields.truncate(4);
let [uid, name, description, filename] = <[String; 4]>::try_from(fields).ok()?;
Some((uid.to_ascii_lowercase(), BadgeInfo { name, description, filename }))
})
.collect()
});
/// What a badge GUID stands for; none for one the table does not know.
pub fn info(guid: &str) -> Option<&'static BadgeInfo> {
BADGES.get(&guid.to_ascii_lowercase())
}
/// The address of a badge's picture (an SVG); none for an unknown badge.
pub fn icon_url(guid: &str) -> Option<String> {
let info = info(guid)?;
Some(format!("{CONTENT}/{}/{}.svg", guid.to_ascii_lowercase(), info.filename))
}
/// The records of a CSV text (RFC 4180): fields split at commas; a quoted
/// field may hold commas and line breaks, and `""` for a quote.
fn records(text: &str) -> Vec<Vec<String>> {
let mut records = Vec::new();
let mut record = Vec::new();
let mut field = String::new();
let mut quoted = false;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' if quoted => {
if chars.next_if_eq(&'"').is_some() {
field.push('"');
} else {
quoted = false;
}
}
'"' if field.is_empty() => quoted = true,
',' if !quoted => record.push(std::mem::take(&mut field)),
'\r' if !quoted => {}
'\n' if !quoted => {
record.push(std::mem::take(&mut field));
records.push(std::mem::take(&mut record));
}
c => field.push(c),
}
}
if !field.is_empty() || !record.is_empty() {
record.push(field);
records.push(record);
}
records
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_badges() {
let info = info("4b27be5a-b92a-4b30-8b2d-14b59653f427").unwrap();
assert_eq!(info.name, "20th Anniversary");
assert_eq!(info.description, "Celebrating 20 Years of TeamSpeak");
assert_eq!(info.filename, "20_years");
// Upper case on the wire finds it too.
assert_eq!(super::info("4B27BE5A-B92A-4B30-8B2D-14B59653F427"), Some(info));
assert_eq!(
icon_url("4b27be5a-b92a-4b30-8b2d-14b59653f427").as_deref(),
Some(
"https://badges-content.teamspeak.com/4b27be5a-b92a-4b30-8b2d-14b59653f427/20_years.svg"
)
);
}
#[test]
fn quoted_fields_keep_their_commas() {
let fools = info("05114019-6b46-4b13-b5a1-e5179ef69fb5").unwrap();
assert_eq!(fools.name, "April Fools!");
assert_eq!(
fools.description,
"Roses are red, gaming is fun, you are carrying too much to be able to run :("
);
assert_eq!(fools.filename, "rpg");
let stay = info("7a627d47-5496-4d68-83b5-2c4eafff9b30").unwrap();
assert_eq!(stay.name, "Stay Home, Stay Safe");
assert_eq!(stay.description, "Playing Apart, Staying Connected");
let up = info("0cd924ed-c5ea-459e-b60a-4f1bc0b65f07").unwrap();
assert_eq!(up.filename, "up,_up_and_away!");
}
#[test]
fn unknown_badges() {
assert_eq!(info("00000000-0000-0000-0000-000000000000"), None);
assert_eq!(info(""), None);
assert_eq!(icon_url("00000000-0000-0000-0000-000000000000"), None);
}
#[test]
fn every_row_is_read() {
let rows = include_str!("../data/badges.csv").lines().count() - 1;
assert_eq!(BADGES.len(), rows);
assert!(BADGES.values().all(|b| !b.name.is_empty() && !b.filename.is_empty()));
}
#[test]
fn csv_records() {
assert_eq!(
records("a,\"b, \"\"c\"\"\",\r\n\"multi\nline\",d"),
[vec!["a", "b, \"c\"", ""], vec!["multi\nline", "d"]]
);
assert!(records("").is_empty());
}
}
-283
View File
@@ -1,283 +0,0 @@
//! Chat messages, from any source.
//!
//! Messages can link files in a channel's file browser: TeamSpeak clients
//! post them as `[URL=ts3file://…]name[/URL]`; [`ChatMessage::file_refs`]
//! finds them as [`FileRef`]s (for file cards) and [`FileRef::to_bbcode`]
//! writes one.
use serde::{Deserialize, Serialize};
use crate::percent;
use crate::presence::{ChannelId, ClientId};
fn is_false(b: &bool) -> bool {
!*b
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
pub enum ChatTarget {
/// Everyone on the server.
Server,
Channel(ChannelId),
/// Private chat, by the other side's unique id when known.
Private(String),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatMessage {
pub target: ChatTarget,
pub author_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub author_uid: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub author_id: Option<ClientId>,
pub text: String,
/// Unix time in milliseconds.
pub ts_ms: i64,
/// Carried by a gateway or query relay rather than our own connection.
#[serde(default)]
pub via_relay: bool,
/// The author is blocked in our contacts (set by the engine when it
/// reports the message; never sent over the wire).
#[serde(default, skip_serializing_if = "is_false")]
pub blocked: bool,
}
impl ChatMessage {
/// The file links in the text, in order of appearance, each once.
pub fn file_refs(&self) -> Vec<FileRef> {
parse_file_links(&self.text)
}
}
/// A file in a channel's file browser, as a chat message links it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct FileRef {
/// The server's unique id (`serverUID`), when the link tells it: a link
/// from another server cannot be downloaded here.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub server_uid: Option<String>,
pub channel: ChannelId,
/// The directory, `/` for the channel's root.
pub path: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u64>,
#[serde(default, skip_serializing_if = "is_false")]
pub is_dir: bool,
/// Unix seconds of the last change, when the link tells it.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub modified_s: Option<i64>,
/// The link as it appeared.
pub url: String,
}
/// URL schemes of file links (`ts3file`; later clients may use others of
/// the same form).
const FILE_SCHEMES: &[&str] = &["ts3file://", "tsfile://", "ts5file://", "ts6file://"];
impl FileRef {
/// The file's path in the channel: [`Self::path`] joined with [`Self::name`].
pub fn full_path(&self) -> String {
let dir = self.path.trim_end_matches('/');
format!("{dir}/{}", self.name)
}
/// Parse one link (`ts3file://name?serverUID=…&channel=…&path=…&filename=…&isDir=…&size=…&fileDateTime=…`).
pub fn parse(url: &str) -> Option<Self> {
let lower = url.get(..12).unwrap_or(url).to_ascii_lowercase();
let scheme = FILE_SCHEMES.iter().find(|s| lower.starts_with(**s))?;
let rest = &url[scheme.len()..];
let (host, query) = rest.split_once('?').unwrap_or((rest, ""));
let mut file = FileRef { url: url.to_owned(), path: "/".into(), ..Default::default() };
let mut channel = None;
for pair in query.split('&') {
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
let value = percent::decode(value);
match key.to_ascii_lowercase().as_str() {
"serveruid" => file.server_uid = Some(value).filter(|v| !v.is_empty()),
"channel" | "cid" => channel = value.parse().ok(),
"path" => file.path = if value.is_empty() { "/".into() } else { value },
"filename" | "name" => file.name = value,
"isdir" => file.is_dir = matches!(value.as_str(), "1" | "true"),
"size" => file.size = value.parse().ok(),
"filedatetime" => file.modified_s = value.parse().ok(),
_ => {}
}
}
if file.name.is_empty() {
file.name = percent::decode(host.trim_end_matches('/'));
}
file.channel = channel?;
(!file.name.is_empty()).then_some(file)
}
/// The link as TeamSpeak clients post it: `[URL=ts3file://…]name[/URL]`.
pub fn to_bbcode(&self) -> String {
let mut url = format!("ts3file://{}?", percent::encode(&self.name));
if let Some(uid) = &self.server_uid {
url.push_str(&format!("serverUID={}&", percent::encode(uid)));
}
url.push_str(&format!(
"channel={}&path={}&filename={}&isDir={}",
self.channel,
percent::encode(&self.path),
percent::encode(&self.name),
u8::from(self.is_dir)
));
if let Some(size) = self.size {
url.push_str(&format!("&size={size}"));
}
if let Some(t) = self.modified_s {
url.push_str(&format!("&fileDateTime={t}"));
}
format!("[URL={url}]{}[/URL]", self.name)
}
}
/// The file links in `text` (BBCode `[URL=…]`, `[URL]…[/URL]`, Markdown
/// `[name](…)` or bare), in order, each once.
pub fn parse_file_links(text: &str) -> Vec<FileRef> {
let lower = text.to_ascii_lowercase();
let mut found: Vec<FileRef> = Vec::new();
let mut at = 0;
while at < text.len() {
let next = FILE_SCHEMES.iter().filter_map(|s| lower[at..].find(s).map(|i| at + i)).min();
let Some(start) = next else { break };
let end = text[start..]
.find(|c: char| c.is_whitespace() || matches!(c, ']' | '[' | ')' | '"' | '<' | '>'))
.map_or(text.len(), |i| start + i);
if let Some(file) = FileRef::parse(&text[start..end])
&& !found.iter().any(|f| f.url == file.url)
{
found.push(file);
}
at = end.max(start + 1);
}
found
}
/// Format of messages a relay posts on behalf of a user.
pub fn relay_text(format: &str, nick: &str, text: &str) -> String {
format.replace("{nick}", nick).replace("{text}", text)
}
/// Split text so each part fits TeamSpeak's message limit (1024 bytes of
/// text), breaking at character boundaries.
pub fn split_message(text: &str, max_bytes: usize) -> Vec<String> {
let mut parts = Vec::new();
let mut current = String::new();
for c in text.chars() {
if current.len() + c.len_utf8() > max_bytes {
parts.push(std::mem::take(&mut current));
}
current.push(c);
}
if !current.is_empty() || parts.is_empty() {
parts.push(current);
}
parts
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn relay_format() {
assert_eq!(relay_text("[{nick}] {text}", "Alice", "hi"), "[Alice] hi");
}
#[test]
fn splits_on_char_boundaries() {
assert_eq!(split_message("abcdef", 4), vec!["abcd", "ef"]);
assert_eq!(split_message("", 4), vec![""]);
let parts = split_message("ääää", 3);
assert!(parts.iter().all(|p| p.len() <= 3));
assert_eq!(parts.concat(), "ääää");
}
#[test]
fn parses_ts3_file_links() {
let text = "look: [URL=ts3file://Report%20Q3.pdf?serverUID=l%2FHvD5zXg5r4%2F%2FC6Ht7J9Ts3Wmc%3D&channel=5&path=%2Fdocs&filename=Report%20Q3.pdf&isDir=0&size=12345&fileDateTime=1454598011]Report Q3.pdf[/URL] and [URL]ts3file://a.txt?channel=1&path=%2F&filename=a+b.txt[/URL]";
let files = parse_file_links(text);
assert_eq!(files.len(), 2);
let f = &files[0];
assert_eq!(f.server_uid.as_deref(), Some("l/HvD5zXg5r4//C6Ht7J9Ts3Wmc="));
assert_eq!((f.channel, f.path.as_str(), f.name.as_str()), (5, "/docs", "Report Q3.pdf"));
assert_eq!((f.size, f.modified_s, f.is_dir), (Some(12345), Some(1_454_598_011), false));
assert_eq!(f.full_path(), "/docs/Report Q3.pdf");
assert_eq!(files[1].name, "a+b.txt");
assert_eq!(files[1].full_path(), "/a+b.txt");
}
#[test]
fn file_links_in_other_forms() {
// Markdown, bare, a repeated link, a link without a channel.
let text = "[x](ts3file://x?channel=2&filename=x&isDir=true) ts3file://y?channel=3&path=/d/ \
ts3file://y?channel=3&path=/d/ ts3file://z?filename=z";
let files = parse_file_links(text);
assert_eq!(files.len(), 2);
assert!(files[0].is_dir);
assert_eq!((files[1].name.as_str(), files[1].full_path().as_str()), ("y", "/d/y"));
let msg = ChatMessage {
target: ChatTarget::Channel(1),
author_name: "a".into(),
author_uid: None,
author_id: None,
text: text.into(),
ts_ms: 0,
via_relay: false,
blocked: false,
};
assert_eq!(msg.file_refs(), files);
assert!(parse_file_links("no links, ts3file:// alone").is_empty());
}
#[test]
fn file_link_round_trip() {
let file = FileRef {
server_uid: Some("uid+/=".into()),
channel: 7,
path: "/a dir".into(),
name: "ä b&c.png".into(),
size: Some(10),
is_dir: false,
modified_s: Some(99),
url: String::new(),
};
let text = file.to_bbcode();
let parsed = parse_file_links(&text);
assert_eq!(parsed.len(), 1);
assert_eq!(FileRef { url: String::new(), ..parsed[0].clone() }, file);
assert!(text.ends_with("]ä b&c.png[/URL]"));
}
#[test]
fn blocked_flag_stays_off_the_wire() {
let msg = ChatMessage {
target: ChatTarget::Server,
author_name: "a".into(),
author_uid: None,
author_id: None,
text: "t".into(),
ts_ms: 1,
via_relay: false,
blocked: false,
};
let json = serde_json::to_string(&msg).unwrap();
assert!(!json.contains("blocked"));
let back: ChatMessage = serde_json::from_str(&json).unwrap();
assert_eq!(back, msg);
}
#[test]
fn target_json() {
assert_eq!(
serde_json::to_string(&ChatTarget::Channel(5)).unwrap(),
r#"{"kind":"channel","id":5}"#
);
assert_eq!(serde_json::to_string(&ChatTarget::Server).unwrap(), r#"{"kind":"server"}"#);
}
}
-23
View File
@@ -1,23 +0,0 @@
//! Domain model shared by the client engine, the gateway and the UI.
//!
//! Nothing in here does IO; the types describe what a server offers and what
//! the user sees.
pub mod badges;
mod chat;
mod link;
mod percent;
mod presence;
mod server;
mod tree;
pub use chat::{ChatMessage, ChatTarget, FileRef, parse_file_links, relay_text, split_message};
pub use link::{Link, ServerLink, channel_path_id, join_channel_path, split_channel_path};
pub use presence::{
ChannelId, ChannelInfo, ClientId, ClientInfo, GroupId, GroupInfo, GroupNamingMode, GroupType,
Presence, PresenceDelta, PresenceSnapshot, myts_avatar_url, parse_badges, shown_badges,
};
pub use server::{
BannerMode, Capabilities, HostMessageMode, ServerDetails, ServerFlavor, ServerVersion,
};
pub use tree::{Spacer, TreeRow, channel_title, order_siblings, parse_spacer, tree_rows};
-420
View File
@@ -1,420 +0,0 @@
//! Server links: `ts3server://` (TeamSpeak 3 and 5), `teamspeak://`
//! (TeamSpeak 6) and TeamSpeak's short links on `tmspk.gg`, whose page sends
//! the browser on to a `teamspeak://` link.
use crate::percent;
use crate::presence::ChannelId;
/// What a link opens ([`Link::parse`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Link {
/// A server, and maybe a channel on it.
Server(ServerLink),
/// A TeamSpeak 6 invite code (`tmspk.gg/<code>`,
/// `teamspeak://invite=<code>`): only a TeamSpeak service knows the
/// server it stands for.
Invite(String),
}
/// A server link: the server, and what to join it with (none of it empty).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ServerLink {
/// A host name, an IP address (IPv6 without brackets) or a server
/// nickname.
pub host: String,
pub port: Option<u16>,
pub nickname: Option<String>,
/// The server's password.
pub password: Option<String>,
/// The channel to join: its names from the top, separated by `/` (a `/`
/// in a name as `\/`, [`split_channel_path`]), or `/<id>` (`cid=`).
pub channel: Option<String>,
pub channel_password: Option<String>,
/// A privilege key: it puts its user in a server or channel group.
pub token: Option<String>,
}
const SCHEMES: [&str; 2] = ["ts3server://", "teamspeak://"];
const WEB: [&str; 2] = ["https://", "http://"];
const SHORT_HOSTS: [&str; 2] = ["tmspk.gg", "www.tmspk.gg"];
impl Link {
/// Read a link: `ts3server://<host>?<query>` with the keys `port`,
/// `nickname`, `password`, `channel` (`A/B`), `cid`, `channelpassword`
/// and `token` (`teamspeak://` alike; the scheme and the keys in any
/// case, other keys ignored, a `+` kept as it is),
/// `https://tmspk.gg/s/<host>?<query>` (also `/s=<host>`), and the
/// invite codes `tmspk.gg/<code>` and `teamspeak://invite=<code>`. None
/// for anything else.
pub fn parse(text: &str) -> Option<Link> {
let text = text.trim();
// The same length in bytes: an index of one is one of the other.
let lower = text.to_ascii_lowercase();
match SCHEMES.iter().find(|s| lower.starts_with(**s)) {
Some(scheme) => parse_server(&text[scheme.len()..]),
None => parse_short(text, &lower),
}
}
}
impl ServerLink {
/// A link to the server at `address` (`host`, `host:port`, `[v6]`,
/// `[v6]:port` or a bare IPv6 address), joining nothing.
pub fn new(address: &str) -> Self {
let (host, port) = split_address(address.trim());
ServerLink { host: host.to_owned(), port, ..Default::default() }
}
/// The server's address as a bookmark keeps it: `host`, `host:port` or
/// `[v6]:port`.
pub fn address(&self) -> String {
match self.port {
Some(port) if self.host.contains(':') => format!("[{}]:{port}", self.host),
Some(port) => format!("{}:{port}", self.host),
None => self.host.clone(),
}
}
/// The link as TeamSpeak clients open it: `ts3server://<host>?port=…`,
/// then what is set of nickname, password, channel (or `cid` for
/// `/<id>`), channel password and privilege key.
pub fn to_url(&self) -> String {
let mut url = match self.port {
Some(_) if self.host.contains(':') => format!("ts3server://[{}]", self.host),
_ => format!("ts3server://{}", self.host),
};
let pair = |key: &str, value: &Option<String>| {
let value = value.as_deref().filter(|v| !v.is_empty())?;
Some(format!("{key}={}", percent::encode(value)))
};
let channel = self.channel.as_deref().filter(|c| !c.is_empty()).map(|path| {
match channel_path_id(path) {
Some(id) => format!("cid={id}"),
// A `/` between names, `%2F` in one.
None => {
let names: Vec<String> =
split_channel_path(path).iter().map(|n| percent::encode(n)).collect();
format!("channel={}", names.join("/"))
}
}
});
let query: Vec<String> = [
self.port.map(|port| format!("port={port}")),
pair("nickname", &self.nickname),
pair("password", &self.password),
channel,
pair("channelpassword", &self.channel_password),
pair("token", &self.token),
]
.into_iter()
.flatten()
.collect();
if !query.is_empty() {
url.push('?');
url.push_str(&query.join("&"));
}
url
}
}
/// A channel path's names from the top: `Gaming/Raid Night` →
/// `["Gaming", "Raid Night"]`, `AC\/DC` → `["AC/DC"]`.
pub fn split_channel_path(path: &str) -> Vec<String> {
let mut names = Vec::new();
let mut name = String::new();
let mut chars = path.chars().peekable();
while let Some(c) = chars.next() {
match c {
'\\' if chars.peek() == Some(&'/') => {
name.push('/');
chars.next();
}
'/' => names.push(std::mem::take(&mut name)),
c => name.push(c),
}
}
names.push(name);
names
}
/// A channel path from its names from the top, a `/` in a name as `\/`:
/// the reverse of [`split_channel_path`].
pub fn join_channel_path(names: &[impl AsRef<str>]) -> String {
names.iter().map(|n| n.as_ref().replace('/', "\\/")).collect::<Vec<_>>().join("/")
}
/// The channel id of a path `/<id>` (what `cid=` gives).
pub fn channel_path_id(path: &str) -> Option<ChannelId> {
let id = path.strip_prefix('/')?;
if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
id.parse().ok()
}
/// After `ts3server://` or `teamspeak://`: `<host>[:port][/]?<query>`, or
/// `invite=<code>`.
fn parse_server(rest: &str) -> Option<Link> {
let (head, query) = rest.split_once('?').unwrap_or((rest, ""));
let authority = head.split('/').next().unwrap_or_default();
if let Some(key) = authority.get(..7).filter(|k| k.eq_ignore_ascii_case("invite=")) {
let code = percent::decode(&authority[key.len()..]);
return (!code.is_empty()).then_some(Link::Invite(code));
}
let authority = percent::decode(authority);
let (host, port) = split_address(&authority);
if host.is_empty() || host.chars().any(|c| c.is_whitespace() || c.is_control()) {
return None;
}
let mut link = ServerLink { host: host.to_owned(), port, ..Default::default() };
let mut cid = None;
for pair in query.split('&') {
let (key, raw) = pair.split_once('=').unwrap_or((pair, ""));
let value = Some(percent::decode(raw)).filter(|v| !v.is_empty());
match key.to_ascii_lowercase().as_str() {
// One that is no port is ignored.
"port" => link.port = value.as_deref().and_then(parse_port).or(link.port),
"nickname" => link.nickname = value,
"password" => link.password = value,
// A `/` between names, `%2F` in one.
"channel" => {
let names: Vec<String> = raw.split('/').map(percent::decode).collect();
link.channel = Some(join_channel_path(&names)).filter(|_| names.concat() != "");
}
"cid" => cid = value.and_then(|v| v.parse::<ChannelId>().ok()).filter(|c| *c != 0),
"channelpassword" => link.channel_password = value,
"token" => link.token = value,
_ => {}
}
}
// The id names one channel for sure.
if let Some(cid) = cid {
link.channel = Some(format!("/{cid}"));
}
Some(Link::Server(link))
}
/// `tmspk.gg/s/<host>?…` (or `/s=`), with or without `https://`, goes where
/// its page sends the browser: `teamspeak://<host>?…`; any other path is an
/// invite code.
fn parse_short(text: &str, lower: &str) -> Option<Link> {
let start = WEB.iter().find(|s| lower.starts_with(**s)).map_or(0, |s| s.len());
let (host, path) = text[start..].split_once('/')?;
if !SHORT_HOSTS.contains(&host.to_ascii_lowercase().as_str()) {
return None;
}
if path.get(..2).is_some_and(|s| s.eq_ignore_ascii_case("s/") || s.eq_ignore_ascii_case("s=")) {
return parse_server(&path[2..]);
}
let code = path.split(['?', '#', '/']).next().unwrap_or_default();
let valid = |b: u8| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_');
(!code.is_empty() && code.bytes().all(valid)).then(|| Link::Invite(code.to_owned()))
}
/// `host`, `host:port`, `[v6]`, `[v6]:port` or a bare IPv6 address: the
/// host (an IPv6 address without its brackets) and the port, if one is
/// given that is one.
fn split_address(address: &str) -> (&str, Option<u16>) {
if let Some((host, after)) = address.strip_prefix('[').and_then(|a| a.split_once(']')) {
return (host, after.strip_prefix(':').and_then(parse_port));
}
match address.rsplit_once(':') {
// A port follows the only colon; more colons: an IPv6 address.
Some((host, port))
if !host.contains(':')
&& !port.is_empty()
&& port.bytes().all(|b| b.is_ascii_digit()) =>
{
(host, parse_port(port))
}
_ => (address, None),
}
}
fn parse_port(text: &str) -> Option<u16> {
text.parse().ok().filter(|p| *p != 0)
}
#[cfg(test)]
mod tests {
use super::*;
fn server(text: &str) -> ServerLink {
match Link::parse(text) {
Some(Link::Server(link)) => link,
other => panic!("{text}: {other:?}"),
}
}
fn host(host: &str, port: Option<u16>) -> ServerLink {
ServerLink { host: host.into(), port, ..Default::default() }
}
#[test]
fn every_parameter() {
let link = server(
"ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid+1&token=AbC%2Bd&addbookmark=Mine",
);
assert_eq!(
link,
ServerLink {
host: "ts.example.org".into(),
port: Some(9988),
nickname: Some("Nova X".into()),
password: Some("s3cr?t".into()),
channel: Some("Gaming/Raid Night".into()),
// A `+` stays.
channel_password: Some("raid+1".into()),
token: Some("AbC+d".into()),
}
);
assert_eq!(link.address(), "ts.example.org:9988");
assert_eq!(
link.to_url(),
"ts3server://ts.example.org?port=9988&nickname=Nova%20X&password=s3cr%3Ft&channel=Gaming/Raid%20Night&channelpassword=raid%2B1&token=AbC%2Bd"
);
assert_eq!(Link::parse(&link.to_url()), Some(Link::Server(link)));
// A channel id names the channel, also next to a path.
assert_eq!(server("ts3server://h?cid=12").channel.as_deref(), Some("/12"));
assert_eq!(server("ts3server://h?channel=Lobby&cid=12").channel.as_deref(), Some("/12"));
assert_eq!(server("ts3server://h?cid=x&channel=Lobby").channel.as_deref(), Some("Lobby"));
assert_eq!(server("ts3server://h?cid=12").to_url(), "ts3server://h?cid=12");
// Empty values are none.
assert_eq!(server("ts3server://h?nickname=&channel=&password"), host("h", None));
}
#[test]
fn teamspeak_scheme_is_the_same() {
let query = "ts.example.org?port=9987&channel=Lobby&nickname=Nova";
assert_eq!(
Link::parse(&format!("teamspeak://{query}")),
Link::parse(&format!("ts3server://{query}"))
);
// Any case, of the scheme and the keys; the host as written.
let link = server("TeamSpeak://TS.Example.org/?PORT=9988&Channel=Lobby&CID=");
assert_eq!(
link,
ServerLink { channel: Some("Lobby".into()), ..host("TS.Example.org", Some(9988)) }
);
assert_eq!(server("TS3SERVER://h:9988"), host("h", Some(9988)));
}
#[test]
fn short_links() {
for text in [
"https://tmspk.gg/s/ts.example.org?port=9988&channel=Lobby",
"https://tmspk.gg/s=ts.example.org?port=9988&channel=Lobby",
"HTTPS://www.TMSPK.gg/S/ts.example.org?port=9988&channel=Lobby",
"tmspk.gg/s/ts.example.org/?port=9988&channel=Lobby",
"http://tmspk.gg/s/ts.example.org:9988?channel=Lobby",
] {
assert_eq!(
server(text),
ServerLink { channel: Some("Lobby".into()), ..host("ts.example.org", Some(9988)) },
"{text}"
);
}
let invite = |code: &str| Some(Link::Invite(code.into()));
assert_eq!(Link::parse("https://tmspk.gg/AbC12x"), invite("AbC12x"));
assert_eq!(Link::parse("tmspk.gg/AbC12x/?ref=1"), invite("AbC12x"));
assert_eq!(Link::parse("teamspeak://invite=AbC12x"), invite("AbC12x"));
assert_eq!(Link::parse("TEAMSPEAK://Invite=AbC12x/"), invite("AbC12x"));
for text in ["https://tmspk.gg/", "https://tmspk.gg", "tmspk.gg/a.b", "teamspeak://invite="]
{
assert_eq!(Link::parse(text), None, "{text}");
}
}
#[test]
fn ipv6() {
let v6 = host("2001:db8::1", Some(9987));
assert_eq!(server("ts3server://[2001:db8::1]?port=9987"), v6);
assert_eq!(server("ts3server://[2001:db8::1]:9987"), v6);
assert_eq!(v6.address(), "[2001:db8::1]:9987");
assert_eq!(v6.to_url(), "ts3server://[2001:db8::1]?port=9987");
// Without a port, with or without brackets.
let bare = host("2001:db8::1", None);
assert_eq!(server("ts3server://2001:db8::1"), bare);
assert_eq!(server("ts3server://[2001:db8::1]"), bare);
assert_eq!(bare.address(), "2001:db8::1");
assert_eq!(ServerLink::new(" [2001:db8::1]:9988 "), host("2001:db8::1", Some(9988)));
}
#[test]
fn escapes() {
let link = server("ts3server://h?channel=%C3%84rger/Caf%C3%A9&nickname=J%C3%BCrgen");
assert_eq!(link.channel.as_deref(), Some("Ärger/Café"));
assert_eq!(link.nickname.as_deref(), Some("Jürgen"));
// `%2F` is a `/` in a name.
let link = server("ts3server://h?channel=AC%2FDC/Live");
assert_eq!(link.channel.as_deref(), Some("AC\\/DC/Live"));
assert_eq!(split_channel_path("AC\\/DC/Live"), ["AC/DC", "Live"]);
assert_eq!(join_channel_path(&["AC/DC", "Live"]), "AC\\/DC/Live");
assert_eq!(link.to_url(), "ts3server://h?channel=AC%2FDC/Live");
assert_eq!(split_channel_path("Lobby"), ["Lobby"]);
assert_eq!(channel_path_id("/12"), Some(12));
assert_eq!(channel_path_id("12"), None);
assert_eq!(channel_path_id("/1a"), None);
}
#[test]
fn invalid_ports_are_ignored() {
for text in [
"ts3server://h?port=abc",
"ts3server://h?port=70000",
"ts3server://h?port=0",
"ts3server://h?port=",
"ts3server://h:70000",
] {
assert_eq!(server(text), host("h", None), "{text}");
}
// One in the address stays.
assert_eq!(server("ts3server://h:9988?port=x"), host("h", Some(9988)));
}
#[test]
fn other_links_are_none() {
for text in [
"",
"http://example.com",
"https://example.com/s/ts.example.org",
"ts3file://a.png?serverUID=x&channel=1",
"ts3server://",
"ts3server://?port=9987",
"ts3server://a b",
"ts.example.org",
"mailto:a@example.org",
] {
assert_eq!(Link::parse(text), None, "{text:?}");
}
}
#[test]
fn round_trip() {
// The invite links of voelin-ui (`vm::servers::invite_link`).
for (address, names, url) in [
(
"ts.example.com:9988",
&["Gaming", "Raid Night"][..],
"ts3server://ts.example.com?port=9988&channel=Gaming/Raid%20Night",
),
(" ts.example.com ", &[], "ts3server://ts.example.com"),
(
"[2001:db8::1]:9987",
&["Chill & Co"],
"ts3server://[2001:db8::1]?port=9987&channel=Chill%20%26%20Co",
),
("2001:db8::1", &[], "ts3server://2001:db8::1"),
("h:x", &["Ä/b"], "ts3server://h:x?channel=%C3%84%2Fb"),
] {
let mut link = ServerLink::new(address);
link.channel = (!names.is_empty()).then(|| join_channel_path(names));
assert_eq!(link.to_url(), url);
assert_eq!(Link::parse(url), Some(Link::Server(link.clone())), "{url}");
assert_eq!(link.address(), address.trim());
if let Some(path) = &link.channel {
assert_eq!(split_channel_path(path), names);
}
}
}
}
-54
View File
@@ -1,54 +0,0 @@
//! Percent escapes in links: file links ([`crate::FileRef`]) and server
//! links ([`crate::Link`]).
/// `%XX` escapes to bytes, read as UTF-8 (a `+` stays: file names and
/// passwords keep theirs).
pub(crate) fn decode(s: &str) -> String {
let bytes = s.as_bytes();
let hex = |b: u8| (b as char).to_digit(16);
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let (Some(h), Some(l)) =
(bytes.get(i + 1).and_then(|b| hex(*b)), bytes.get(i + 2).and_then(|b| hex(*b)))
{
out.push((h * 16 + l) as u8);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
/// Every byte but letters, digits and `-._~` as `%XX`.
pub(crate) fn encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn escapes() {
assert_eq!(decode("Raid%20Night"), "Raid Night");
assert_eq!(decode("%C3%84b"), "Äb");
assert_eq!(decode("a+b"), "a+b");
// A broken escape stays as it is.
assert_eq!(decode("100%"), "100%");
assert_eq!(decode("%zz"), "%zz");
assert_eq!(encode("Chill & Co/Ä"), "Chill%20%26%20Co%2F%C3%84");
assert_eq!(decode(&encode("a b+c%")), "a b+c%");
}
}
-493
View File
@@ -1,493 +0,0 @@
//! Who is where: channels and the clients in them.
//!
//! The same model is fed from a voice connection, a query session or a
//! gateway. Sources send a [`PresenceSnapshot`] followed by
//! [`PresenceDelta`]s; sources that can only poll use [`Presence::diff`].
//!
//! A voice connection also knows the server's details (welcome message,
//! host banner, …) and its server and channel groups ([`Presence::server`],
//! [`Presence::server_groups`], [`Presence::channel_groups`]); snapshots and
//! deltas do not carry them (other sources leave them empty).
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::server::{BannerMode, ServerDetails};
pub type ChannelId = u64;
pub type ClientId = u16;
/// A server or channel group id.
pub type GroupId = u64;
fn is_zero_i32(n: &i32) -> bool {
*n == 0
}
fn is_zero_u32(n: &u32) -> bool {
*n == 0
}
fn is_false(b: &bool) -> bool {
!*b
}
fn is_default<T: Default + PartialEq>(v: &T) -> bool {
*v == T::default()
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChannelInfo {
pub id: ChannelId,
/// `0` for top-level channels.
pub parent: ChannelId,
/// Id of the sibling directly above, `0` for the first.
pub order: ChannelId,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub topic: Option<String>,
#[serde(default)]
pub has_password: bool,
/// `None` means unlimited.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_clients: Option<i32>,
#[serde(default)]
pub needed_subscribe_power: i32,
#[serde(default)]
pub needed_talk_power: i32,
#[serde(default)]
pub is_default: bool,
/// Icon id (`channel_icon_id`); 0: none.
#[serde(default, skip_serializing_if = "is_zero_u32")]
pub icon: u32,
/// The address of the channel's banner picture (TeamSpeak 6,
/// `channel_banner_gfx_url`), drawn behind the channel.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub banner_gfx_url: Option<String>,
#[serde(default, skip_serializing_if = "is_default")]
pub banner_mode: BannerMode,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClientInfo {
pub id: ClientId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uid: Option<String>,
pub nickname: String,
pub channel: ChannelId,
/// ServerQuery clients (bots, our own relays). UIs normally hide them.
#[serde(default)]
pub is_query: bool,
/// Away, with the away message (empty without one); `None`: not away.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub away: Option<String>,
#[serde(default)]
pub input_muted: bool,
#[serde(default)]
pub output_muted: bool,
/// `None` when the source cannot tell (query sessions see no voice).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub talking: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub streaming: Option<bool>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub server_groups: Vec<GroupId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
/// MD5 hash of the client's avatar (`client_flag_avatar`, hex); `None`:
/// no avatar. A new hash means a new avatar.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub avatar: Option<String>,
/// The myTeamSpeak avatar's picture (TeamSpeak 6, an HTTPS link from
/// `client_myteamspeak_avatar`, [`myts_avatar_url`]): shown where the
/// server has no avatar for the client.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub myts_avatar: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "is_zero_i32")]
pub talk_power: i32,
/// Allowed to talk regardless of talk power (`client_is_talker`).
#[serde(default, skip_serializing_if = "is_false")]
pub talker: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel_group: Option<GroupId>,
/// Badge GUIDs, in display order ([`shown_badges`]).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub badges: Vec<String>,
/// Icon id (`client_icon_id`); 0: none.
#[serde(default, skip_serializing_if = "is_zero_u32")]
pub icon: u32,
#[serde(default, skip_serializing_if = "is_false")]
pub recording: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub priority_speaker: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub channel_commander: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub database_id: Option<u64>,
}
/// Badge GUIDs of a `client_badges` value
/// (`Overwolf=0:badges=<guid>,<guid>`).
pub fn parse_badges(value: &str) -> Vec<String> {
value
.split(':')
.filter_map(|part| part.strip_prefix("badges="))
.flat_map(|list| list.split(','))
.map(str::trim)
.filter(|g| !g.is_empty())
.map(str::to_owned)
.collect()
}
/// The badges a client shows: those a TeamSpeak 6 server verified
/// (`client_signed_badges`, ids joined by `,`) first, then those of its
/// `client_badges` ([`parse_badges`]), each once.
pub fn shown_badges(badges: &str, signed: &str) -> Vec<String> {
let signed = signed.split(',').map(str::trim).filter(|g| !g.is_empty()).map(str::to_owned);
let mut shown: Vec<String> = Vec::new();
for guid in signed.chain(parse_badges(badges)) {
if !shown.iter().any(|g| g.eq_ignore_ascii_case(&guid)) {
shown.push(guid);
}
}
shown
}
/// The picture to show of a `client_myteamspeak_avatar` value (TeamSpeak
/// 6): `<state>,<url>;<state>,<url>…`, states as myTeamSpeak's
/// `AvatarState` (1 do not disturb, 2 online, 3 away, 4 offline). As the
/// official client reads it: an entry that is not `<number>,<url>` (an
/// empty one too, from a trailing `;`) makes the whole value no avatar;
/// the "online" picture is shown whatever the client's state (an unknown
/// state counts as online), else away, do not disturb, offline, the first
/// of a kind. Only an HTTPS link of at most 4 KiB.
pub fn myts_avatar_url(value: &str) -> Option<String> {
let mut best: Option<(u8, &str)> = None;
for entry in value.split(';') {
let mut parts = entry.split(',');
let state: u32 = parts.next()?.trim().parse().ok()?;
let url = parts.next()?.trim();
let rank = match state {
3 => 1,
1 => 2,
4 => 3,
_ => 0,
};
if best.is_none_or(|(r, _)| rank < r) {
best = Some((rank, url));
}
}
let url = best?.1;
(url.starts_with("https://") && url.len() <= 4096).then(|| url.to_owned())
}
/// How a group's name is shown next to its members.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GroupNamingMode {
#[default]
None,
/// Before the nickname: `[Admin] Alice`.
Before,
/// After the nickname: `Alice [Admin]`.
After,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GroupType {
/// For new virtual servers; nobody is a member.
Template,
#[default]
Regular,
/// ServerQuery clients.
Query,
}
/// A server or channel group.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct GroupInfo {
pub id: GroupId,
pub name: String,
/// Icon id; 0: none.
#[serde(default, skip_serializing_if = "is_zero_u32")]
pub icon: u32,
/// Display order: lower first, then by id.
#[serde(default)]
pub sort_id: i32,
#[serde(default)]
pub naming_mode: GroupNamingMode,
#[serde(default)]
pub group_type: GroupType,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PresenceSnapshot {
pub server_name: String,
pub channels: Vec<ChannelInfo>,
pub clients: Vec<ClientInfo>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum PresenceDelta {
ChannelAdded(ChannelInfo),
ChannelChanged(ChannelInfo),
ChannelRemoved { id: ChannelId },
ClientJoined(ClientInfo),
ClientChanged(ClientInfo),
ClientMoved { id: ClientId, channel: ChannelId },
ClientLeft { id: ClientId },
ServerRenamed { name: String },
}
/// Current state; apply deltas as they arrive.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Presence {
pub server_name: String,
pub channels: BTreeMap<ChannelId, ChannelInfo>,
pub clients: BTreeMap<ClientId, ClientInfo>,
/// What the source knows about the server (a voice connection: all of
/// it; other sources: nothing).
pub server: ServerDetails,
pub server_groups: BTreeMap<GroupId, GroupInfo>,
pub channel_groups: BTreeMap<GroupId, GroupInfo>,
}
impl Presence {
pub fn from_snapshot(s: PresenceSnapshot) -> Self {
Self {
server_name: s.server_name,
channels: s.channels.into_iter().map(|c| (c.id, c)).collect(),
clients: s.clients.into_iter().map(|c| (c.id, c)).collect(),
..Self::default()
}
}
/// The client with this unique id, if present (the first of several
/// connections with the same identity).
pub fn client_by_uid(&self, uid: &str) -> Option<&ClientInfo> {
self.clients.values().find(|c| c.uid.as_deref() == Some(uid))
}
/// Groups in display order (sort id, then id).
pub fn sorted_groups(groups: &BTreeMap<GroupId, GroupInfo>) -> Vec<&GroupInfo> {
let mut sorted: Vec<_> = groups.values().collect();
sorted.sort_by_key(|g| (g.sort_id, g.id));
sorted
}
pub fn snapshot(&self) -> PresenceSnapshot {
PresenceSnapshot {
server_name: self.server_name.clone(),
channels: self.channels.values().cloned().collect(),
clients: self.clients.values().cloned().collect(),
}
}
/// Apply a delta. Returns `false` if it referred to something unknown
/// (the caller may want to resynchronise).
pub fn apply(&mut self, delta: &PresenceDelta) -> bool {
match delta {
PresenceDelta::ChannelAdded(c) | PresenceDelta::ChannelChanged(c) => {
self.channels.insert(c.id, c.clone());
true
}
PresenceDelta::ChannelRemoved { id } => self.channels.remove(id).is_some(),
PresenceDelta::ClientJoined(c) | PresenceDelta::ClientChanged(c) => {
self.clients.insert(c.id, c.clone());
true
}
PresenceDelta::ClientMoved { id, channel } => match self.clients.get_mut(id) {
Some(c) => {
c.channel = *channel;
true
}
None => false,
},
PresenceDelta::ClientLeft { id } => self.clients.remove(id).is_some(),
PresenceDelta::ServerRenamed { name } => {
self.server_name = name.clone();
true
}
}
}
/// Deltas that turn `self` into `new`, for sources that poll.
pub fn diff(&self, new: &Presence) -> Vec<PresenceDelta> {
let mut out = Vec::new();
if self.server_name != new.server_name {
out.push(PresenceDelta::ServerRenamed { name: new.server_name.clone() });
}
for (id, c) in &new.channels {
match self.channels.get(id) {
None => out.push(PresenceDelta::ChannelAdded(c.clone())),
Some(old) if old != c => out.push(PresenceDelta::ChannelChanged(c.clone())),
_ => {}
}
}
for (id, c) in &new.clients {
match self.clients.get(id) {
None => out.push(PresenceDelta::ClientJoined(c.clone())),
Some(old) if old == c => {}
Some(old) if ClientInfo { channel: c.channel, ..old.clone() } == *c => {
out.push(PresenceDelta::ClientMoved { id: *id, channel: c.channel });
}
Some(_) => out.push(PresenceDelta::ClientChanged(c.clone())),
}
}
for id in self.clients.keys().filter(|id| !new.clients.contains_key(id)) {
out.push(PresenceDelta::ClientLeft { id: *id });
}
// Channels last, so clients leave a removed channel first.
for id in self.channels.keys().filter(|id| !new.channels.contains_key(id)) {
out.push(PresenceDelta::ChannelRemoved { id: *id });
}
out
}
/// Clients in a channel, excluding query clients.
pub fn members(&self, channel: ChannelId) -> impl Iterator<Item = &ClientInfo> {
self.clients.values().filter(move |c| c.channel == channel && !c.is_query)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ch(id: u64, name: &str) -> ChannelInfo {
ChannelInfo { id, name: name.into(), ..Default::default() }
}
fn cl(id: u16, name: &str, channel: u64) -> ClientInfo {
ClientInfo { id, nickname: name.into(), channel, ..Default::default() }
}
fn presence(channels: Vec<ChannelInfo>, clients: Vec<ClientInfo>) -> Presence {
Presence::from_snapshot(PresenceSnapshot { server_name: "s".into(), channels, clients })
}
#[test]
fn diff_then_apply_reaches_target() {
let old = presence(
vec![ch(1, "Lobby"), ch(2, "Games")],
vec![cl(1, "Alice", 1), cl(2, "Bob", 1), cl(3, "Carol", 2)],
);
let mut muted = cl(2, "Bob", 1);
muted.input_muted = true;
let new = presence(
vec![ch(1, "Lobby"), ch(3, "New")],
vec![cl(1, "Alice", 3), muted, cl(4, "Dave", 1)],
);
let deltas = old.diff(&new);
assert!(deltas.contains(&PresenceDelta::ClientMoved { id: 1, channel: 3 }));
assert!(deltas.contains(&PresenceDelta::ClientLeft { id: 3 }));
assert!(deltas.contains(&PresenceDelta::ChannelRemoved { id: 2 }));
assert!(deltas.iter().any(|d| matches!(d, PresenceDelta::ClientChanged(c) if c.id == 2)));
let mut state = old.clone();
for d in &deltas {
assert!(state.apply(d));
}
assert_eq!(state, new);
assert!(new.diff(&new).is_empty());
}
#[test]
fn myts_avatars_as_the_official_client_reads_them() {
let on = "https://a.example.test/on.png";
assert_eq!(myts_avatar_url(&format!("3,https://a/away;2,{on}")).as_deref(), Some(on));
// Away before do not disturb before offline; the first of a kind.
assert_eq!(
myts_avatar_url("4,https://a/off;1,https://a/dnd;3,https://a/away;3,https://a/b")
.as_deref(),
Some("https://a/away")
);
assert_eq!(
myts_avatar_url("1,https://a/dnd;4,https://a/off").as_deref(),
Some("https://a/dnd")
);
// An unknown state counts as online.
assert_eq!(
myts_avatar_url("3,https://a/away;9,https://a/x").as_deref(),
Some("https://a/x")
);
// One bad entry spoils the value.
for bad in ["", "2", "x,https://a/on", "2,https://a/on;", "2,https://a/on;;3,https://a/b"] {
assert_eq!(myts_avatar_url(bad), None, "{bad:?}");
}
// Only HTTPS, and not endless.
assert_eq!(myts_avatar_url("2,http://a/on"), None);
assert_eq!(myts_avatar_url(&format!("2,https://a/{}", "x".repeat(4096))), None);
// Older JSON without the field still loads.
let client: ClientInfo =
serde_json::from_str(r#"{"id":1,"nickname":"a","channel":1}"#).unwrap();
assert_eq!(client.myts_avatar, None);
}
#[test]
fn badges_and_groups() {
assert_eq!(
parse_badges(
"Overwolf=0:badges=c9e97536-5a2d-4c8e-a135-af404587a472,450f81c1-ab41-4211-a338-222fa94ed157"
),
["c9e97536-5a2d-4c8e-a135-af404587a472", "450f81c1-ab41-4211-a338-222fa94ed157"]
);
assert!(parse_badges("").is_empty());
assert!(parse_badges("Overwolf=1").is_empty());
// TeamSpeak 6's verified badges first, each once.
assert_eq!(
shown_badges(
"Overwolf=0:badges=c9e97536-5a2d-4c8e-a135-af404587a472,450f81c1-ab41-4211-a338-222fa94ed157",
"450F81C1-AB41-4211-A338-222FA94ED157,1cb07348-34a4-4741-b50f-c41e584370f7"
),
[
"450F81C1-AB41-4211-A338-222FA94ED157",
"1cb07348-34a4-4741-b50f-c41e584370f7",
"c9e97536-5a2d-4c8e-a135-af404587a472"
]
);
assert!(shown_badges("", "").is_empty());
let group = |id, sort_id| GroupInfo { id, sort_id, ..Default::default() };
let groups = BTreeMap::from([(1, group(1, 20)), (2, group(2, 10)), (3, group(3, 10))]);
let order: Vec<_> = Presence::sorted_groups(&groups).iter().map(|g| g.id).collect();
assert_eq!(order, [2, 3, 1]);
let mut alice = cl(1, "Alice", 1);
alice.uid = Some("A=".into());
let p = presence(vec![ch(1, "Lobby")], vec![alice, cl(2, "Bob", 1)]);
assert_eq!(p.client_by_uid("A=").map(|c| c.id), Some(1));
assert!(p.client_by_uid("B=").is_none());
}
#[test]
fn old_json_without_new_fields() {
let c: ClientInfo =
serde_json::from_str(r#"{"id":1,"nickname":"a","channel":2,"away":""}"#).unwrap();
assert_eq!(c.away.as_deref(), Some(""));
assert_eq!((c.talk_power, c.avatar.as_ref(), c.badges.len()), (0, None, 0));
// Defaults stay off the wire.
assert_eq!(
serde_json::to_string(&cl(1, "a", 2)).unwrap(),
r#"{"id":1,"nickname":"a","channel":2,"is_query":false,"input_muted":false,"output_muted":false}"#
);
}
#[test]
fn members_skip_query_clients() {
let mut bot = cl(9, "bot", 1);
bot.is_query = true;
let p = presence(vec![ch(1, "Lobby")], vec![cl(1, "Alice", 1), bot]);
assert_eq!(p.members(1).count(), 1);
}
#[test]
fn delta_json_is_tagged() {
let json =
serde_json::to_string(&PresenceDelta::ClientMoved { id: 1, channel: 3 }).unwrap();
assert_eq!(json, r#"{"kind":"client_moved","id":1,"channel":3}"#);
let back: PresenceDelta = serde_json::from_str(&json).unwrap();
assert_eq!(back, PresenceDelta::ClientMoved { id: 1, channel: 3 });
}
}
-250
View File
@@ -1,250 +0,0 @@
//! Server software detection and the capabilities that follow from it.
use std::fmt;
use serde::{Deserialize, Serialize};
/// Parsed `virtualserver_version`, e.g. `3.13.8 [Build: 1779874471]` or
/// `6.0.0-beta13.1 [Build: 1790080330]`.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ServerVersion {
pub major: u32,
pub minor: u32,
pub patch: u32,
/// Pre-release tag such as `beta13.1`.
pub pre: Option<String>,
/// Build timestamp (seconds since the Unix epoch).
pub build: Option<u64>,
}
impl ServerVersion {
pub fn parse(s: &str) -> Option<Self> {
let s = s.trim();
let (version, rest) = s.split_once(' ').unwrap_or((s, ""));
let build = rest
.trim()
.strip_prefix("[Build:")
.and_then(|b| b.strip_suffix(']'))
.and_then(|b| b.trim().parse().ok());
let (numbers, pre) = match version.split_once('-') {
Some((n, p)) => (n, Some(p.to_string())),
None => (version, None),
};
let mut parts = numbers.split('.').map(|p| p.parse::<u32>());
let major = parts.next()?.ok()?;
let minor = parts.next().unwrap_or(Ok(0)).ok()?;
let patch = parts.next().unwrap_or(Ok(0)).ok()?;
Some(Self { major, minor, patch, pre, build })
}
}
impl fmt::Display for ServerVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
if let Some(pre) = &self.pre {
write!(f, "-{pre}")?;
}
Ok(())
}
}
/// Which server software we are talking to.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ServerFlavor {
/// TeamSpeak 3 server (3.x).
Ts3(ServerVersion),
/// TeamSpeak 6 server (6.x; TeamSpeak 5 server betas are treated alike).
Ts6(ServerVersion),
/// Unparseable or unexpected version string.
Unknown(String),
}
impl ServerFlavor {
/// Classify a `virtualserver_version` string.
pub fn from_version_string(s: &str) -> Self {
match ServerVersion::parse(s) {
Some(v) if v.major == 3 => ServerFlavor::Ts3(v),
Some(v) if v.major >= 5 => ServerFlavor::Ts6(v),
_ => ServerFlavor::Unknown(s.to_string()),
}
}
pub fn version(&self) -> Option<&ServerVersion> {
match self {
ServerFlavor::Ts3(v) | ServerFlavor::Ts6(v) => Some(v),
ServerFlavor::Unknown(_) => None,
}
}
pub fn capabilities(&self) -> Capabilities {
match self {
ServerFlavor::Ts3(_) => Capabilities {
streams: false,
raw_query: true,
ssh_query: true,
http_query: false,
file_transfer: true,
offline_messages: true,
},
// Verified against 6.0.0-beta13.1: file transfer and offline
// messages work as on TeamSpeak 3.
ServerFlavor::Ts6(_) => Capabilities {
streams: true,
raw_query: false,
ssh_query: true,
http_query: true,
file_transfer: true,
offline_messages: true,
},
ServerFlavor::Unknown(_) => Capabilities::default(),
}
}
}
/// Where the host message shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HostMessageMode {
/// Not shown.
#[default]
None,
/// In the chat log.
Log,
/// In a dialog.
Modal,
/// In a dialog; the connection ends when it is closed.
ModalQuit,
}
/// How a banner picture (the host banner, a TeamSpeak 6 channel banner) is
/// scaled to its area: `0`, `1` and `2` on the wire.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BannerMode {
/// As it is.
#[default]
NoAdjust,
/// Stretched to the banner area.
IgnoreAspect,
/// Scaled to fit, keeping its aspect ratio.
KeepAspect,
}
impl BannerMode {
/// From its number on the wire; an unknown one shows the picture as it
/// is.
pub fn from_wire(value: &str) -> Self {
match value.trim() {
"1" => Self::IgnoreAspect,
"2" => Self::KeepAspect,
_ => Self::NoAdjust,
}
}
}
/// What a server tells its (voice) clients about itself.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ServerDetails {
pub name: String,
/// `virtualserver_unique_identifier` (the key of its chat history).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub uid: Option<String>,
#[serde(default)]
pub welcome_message: String,
#[serde(default)]
pub host_message: String,
#[serde(default)]
pub host_message_mode: HostMessageMode,
/// Where a click on the banner leads.
#[serde(default)]
pub banner_url: String,
/// The banner image.
#[serde(default)]
pub banner_gfx_url: String,
/// Reload the banner image this often (seconds); 0: never.
#[serde(default)]
pub banner_gfx_interval_s: u64,
#[serde(default)]
pub banner_mode: BannerMode,
#[serde(default)]
pub host_button_tooltip: String,
#[serde(default)]
pub host_button_url: String,
/// The host button's image.
#[serde(default)]
pub host_button_gfx_url: String,
/// Icon id (`virtualserver_icon_id`); 0: none.
#[serde(default)]
pub icon: u32,
/// Server platform, e.g. `Linux`.
#[serde(default)]
pub platform: String,
/// `virtualserver_version`, e.g. `3.13.8 [Build: 1779874471]`.
#[serde(default)]
pub version: String,
#[serde(default)]
pub max_clients: u16,
/// How much everyone else is dimmed while a priority speaker talks
/// (dB, e.g. -18; `virtualserver_priority_speaker_dimm_modificator`,
/// rounded).
#[serde(default)]
pub priority_speaker_dimm_db: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_server_group: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_channel_group: Option<u64>,
}
/// Features that depend on the server software.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Capabilities {
/// Screen sharing / video streams (TeamSpeak 6).
pub streams: bool,
/// Raw TCP ServerQuery (TeamSpeak 3 only; may still be disabled by the admin).
pub raw_query: bool,
/// SSH ServerQuery.
pub ssh_query: bool,
/// HTTP WebQuery (TeamSpeak 6), request/response only, no events.
pub http_query: bool,
/// Channel file browsers, avatars and icons (`ftinit*` over TCP).
#[serde(default)]
pub file_transfer: bool,
/// Offline messages to a unique id (`messageadd`, `messagelist`, …).
#[serde(default)]
pub offline_messages: bool,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_ts3() {
let v = ServerVersion::parse("3.13.8 [Build: 1779874471]").unwrap();
assert_eq!((v.major, v.minor, v.patch), (3, 13, 8));
assert_eq!(v.pre, None);
assert_eq!(v.build, Some(1_779_874_471));
let flavor = ServerFlavor::from_version_string("3.13.8 [Build: 1779874471]");
assert!(matches!(flavor, ServerFlavor::Ts3(_)));
assert!(!flavor.capabilities().streams);
}
#[test]
fn parses_ts6_beta() {
let s = "6.0.0-beta13.1 [Build: 1790080330]";
let v = ServerVersion::parse(s).unwrap();
assert_eq!(v.pre.as_deref(), Some("beta13.1"));
assert_eq!(v.to_string(), "6.0.0-beta13.1");
let flavor = ServerFlavor::from_version_string(s);
assert!(matches!(flavor, ServerFlavor::Ts6(_)));
assert!(flavor.capabilities().streams);
assert!(!flavor.capabilities().raw_query);
}
#[test]
fn handles_garbage() {
assert!(matches!(ServerFlavor::from_version_string(""), ServerFlavor::Unknown(_)));
assert!(matches!(ServerFlavor::from_version_string("x.y"), ServerFlavor::Unknown(_)));
assert_eq!(ServerVersion::parse("3").unwrap().minor, 0);
}
}
-192
View File
@@ -1,192 +0,0 @@
//! Flatten presence into display rows in TeamSpeak's channel order, and
//! read the names of spacer channels.
use std::collections::HashMap;
use crate::presence::{ChannelId, ChannelInfo, ClientInfo, Presence};
/// One line of a channel tree.
#[derive(Clone, Debug, PartialEq)]
pub enum TreeRow<'a> {
Channel { depth: usize, channel: &'a ChannelInfo },
Client { depth: usize, client: &'a ClientInfo },
}
/// Sort siblings by following the `order` links (each channel names the
/// sibling directly above it). Channels whose predecessor is missing are
/// appended at the end, sorted by id, so nothing is ever dropped.
pub fn order_siblings(mut siblings: Vec<&ChannelInfo>) -> Vec<&ChannelInfo> {
siblings.sort_by_key(|c| c.id);
let mut by_prev: HashMap<ChannelId, &ChannelInfo> = HashMap::new();
for c in &siblings {
by_prev.entry(c.order).or_insert(c);
}
let mut sorted = Vec::with_capacity(siblings.len());
let mut prev = 0;
while let Some(c) = by_prev.remove(&prev) {
sorted.push(c);
prev = c.id;
}
for c in siblings {
if !sorted.iter().any(|s| s.id == c.id) {
sorted.push(c);
}
}
sorted
}
/// Channels and their (non-query) clients, depth-first. Clients are sorted by
/// name; `collapsed` channels hide their sub-channels and clients.
pub fn tree_rows<'a>(p: &'a Presence, collapsed: &dyn Fn(ChannelId) -> bool) -> Vec<TreeRow<'a>> {
let mut rows = Vec::new();
add_level(p, 0, 0, collapsed, &mut rows);
rows
}
fn add_level<'a>(
p: &'a Presence,
parent: ChannelId,
depth: usize,
collapsed: &dyn Fn(ChannelId) -> bool,
rows: &mut Vec<TreeRow<'a>>,
) {
let siblings = order_siblings(p.channels.values().filter(|c| c.parent == parent).collect());
for channel in siblings {
rows.push(TreeRow::Channel { depth, channel });
if collapsed(channel.id) {
continue;
}
let mut members: Vec<_> = p.members(channel.id).collect();
members.sort_by(|a, b| a.nickname.to_lowercase().cmp(&b.nickname.to_lowercase()));
for client in members {
rows.push(TreeRow::Client { depth: depth + 1, client });
}
add_level(p, channel.id, depth + 1, collapsed, rows);
}
}
/// How a TeamSpeak spacer channel draws its text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Spacer {
Left,
Center,
Right,
/// The text repeated across the row: a line such as `---`.
Fill,
}
impl Spacer {
/// Whether a spacer with this text only separates the rows around it
/// (a line, or no text): nothing to search for or pick.
pub fn separates(self, text: &str) -> bool {
self == Spacer::Fill || text.trim().is_empty()
}
}
/// A spacer name split into its kind and its text: `[cspacer]Games` is a
/// centred "Games", `[*spacer1]-=` repeats "-=", plain `[spacer3]` is an
/// empty row. The part between `spacer` and `]` only keeps the names
/// unique, so anything goes there. Anything else is not a spacer.
pub fn parse_spacer(name: &str) -> Option<(Spacer, &str)> {
let (inside, text) = name.strip_prefix('[')?.split_once(']')?;
let (kind, _suffix) = inside.split_once("spacer")?;
let kind = match kind {
"" | "l" => Spacer::Left,
"c" => Spacer::Center,
"r" => Spacer::Right,
"*" => Spacer::Fill,
_ => return None,
};
Some((kind, text))
}
/// A channel's name as shown, and its spacer kind. Only top-level channels
/// are spacers, as in TeamSpeak: a sub-channel keeps its name as it is.
/// Names sent to the server (joining by name, invite links) stay raw.
pub fn channel_title(channel: &ChannelInfo) -> (&str, Option<Spacer>) {
match parse_spacer(&channel.name).filter(|_| channel.parent == 0) {
Some((kind, text)) => (text, Some(kind)),
None => (&channel.name, None),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::presence::PresenceSnapshot;
fn ch(id: u64, parent: u64, order: u64, name: &str) -> ChannelInfo {
ChannelInfo { id, parent, order, name: name.into(), ..Default::default() }
}
fn cl(id: u16, name: &str, channel: u64) -> ClientInfo {
ClientInfo { id, nickname: name.into(), channel, ..Default::default() }
}
#[test]
fn follows_order_links() {
let channels = [ch(5, 0, 3, "c"), ch(3, 0, 7, "b"), ch(7, 0, 0, "a")];
let names: Vec<_> =
order_siblings(channels.iter().collect()).iter().map(|c| c.name.as_str()).collect();
assert_eq!(names, ["a", "b", "c"]);
let broken = [ch(1, 0, 0, "a"), ch(2, 0, 99, "orphan")];
assert_eq!(order_siblings(broken.iter().collect())[1].name, "orphan");
}
#[test]
fn rows_depth_first_with_collapse() {
let mut bot = cl(9, "bot", 1);
bot.is_query = true;
let p = Presence::from_snapshot(PresenceSnapshot {
server_name: "s".into(),
channels: vec![ch(1, 0, 0, "Lobby"), ch(2, 0, 1, "Games"), ch(3, 2, 0, "Squad")],
clients: vec![cl(1, "zed", 1), cl(2, "Alice", 1), bot, cl(3, "Bob", 3)],
});
let describe = |rows: Vec<TreeRow>| -> Vec<String> {
rows.iter()
.map(|r| match r {
TreeRow::Channel { depth, channel } => format!("{depth}#{}", channel.name),
TreeRow::Client { depth, client } => format!("{depth}-{}", client.nickname),
})
.collect()
};
assert_eq!(
describe(tree_rows(&p, &|_| false)),
["0#Lobby", "1-Alice", "1-zed", "0#Games", "1#Squad", "2-Bob"]
);
assert_eq!(
describe(tree_rows(&p, &|c| c == 2)),
["0#Lobby", "1-Alice", "1-zed", "0#Games"]
);
}
#[test]
fn spacer_names() {
use Spacer::*;
for (name, spacer) in [
("[spacer0]", Some((Left, ""))),
("[spacer3]Hi", Some((Left, "Hi"))),
("[lspacer]Hi", Some((Left, "Hi"))),
("[rspacer9]Hi", Some((Right, "Hi"))),
("[cspacer]Hi", Some((Center, "Hi"))),
("[cspacerx]Hi", Some((Center, "Hi"))),
("[cspacer12]Гамесы [1]", Some((Center, "Гамесы [1]"))),
("[*spacer1]-=", Some((Fill, "-="))),
("[*spacer]", Some((Fill, ""))),
("[cspacer2Games", None),
("Games", None),
("[Spacer]x", None),
("[xspacer]x", None),
("[spacr]x", None),
("x[spacer]", None),
] {
assert_eq!(parse_spacer(name), spacer, "{name}");
}
assert!(Fill.separates("-=") && Left.separates("") && Center.separates(" "));
assert!(!Left.separates("Hi"));
// Only top-level channels are spacers: a sub-channel keeps its name.
assert_eq!(channel_title(&ch(1, 0, 0, "[rspacer]Staff")), ("Staff", Some(Right)));
assert_eq!(channel_title(&ch(2, 1, 0, "[rspacer]Staff")), ("[rspacer]Staff", None));
assert_eq!(channel_title(&ch(3, 0, 0, "Lobby")), ("Lobby", None));
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ publish.workspace = true
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt", "sync", "time"] }
tracing = "0.1"
voelin-model = { path = "../voelin-model" }
voelin-model = { workspace = true }
voelin-query = { path = "../voelin-query" }
[dev-dependencies]
+9 -4
View File
@@ -24,9 +24,11 @@ tokio = { version = "1", features = ["rt", "sync", "time"] }
tracing = "0.1"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts", "file_chooser", "proxy_resolver"], optional = true }
# `async-io`, not `tokio`, as in voelin-media: GPUI enables ashpd's `async-io` and
# ashpd refuses both features at once.
ashpd = { version = "0.13", default-features = false, features = ["async-io", "global_shortcuts", "file_chooser", "proxy_resolver"], optional = true }
futures-util = { version = "0.3", optional = true }
notify-rust = { version = "4.18", default-features = false, features = ["z-with-tokio"] }
notify-rust = { version = "4.18", default-features = false, features = ["z"] }
x11rb = { version = "0.13", features = ["xinput"], optional = true }
[target.'cfg(windows)'.dependencies]
@@ -46,8 +48,11 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
[target.'cfg(all(unix, not(target_os = "macos")))'.dev-dependencies]
x11rb = { version = "0.13", features = ["xinput", "xtest"] }
# A stand-in desktop portal on a private session bus (tests/proxy.rs); the
# zbus ashpd uses.
zbus = { version = "5", default-features = false, features = ["tokio"] }
# zbus ashpd uses, on `async-io` like every other zbus in the workspace: a
# `tokio` here would put the executor choice of ashpd's connection (zbus picks
# tokio when a tokio runtime is current where it builds the connection) into
# the tests alone, and tests/proxy.rs checks that the choice does not matter.
zbus = { version = "5", default-features = false, features = ["async-io"] }
[lints]
workspace = true
+172 -7
View File
@@ -1,8 +1,15 @@
//! The desktop's proxy through a stand-in xdg-desktop-portal on the
//! session bus. Run it on a private bus:
//! `dbus-run-session -- cargo test -p voelin-platform --test proxy`;
//! without a session bus it checks nothing. Its own test binary: answers
//! are kept process-wide.
//! The desktop's proxy through a stand-in xdg-desktop-portal on a session
//! bus. The test runs itself again under `dbus-run-session` on a bus of its
//! own that starts no services: on a desktop's bus the real portal is running
//! or startable, and when the stand-in leaves the bus (as the test has it do)
//! the real one is started and answers instead. Without `dbus-run-session`,
//! or a bus daemon for it, the test says so and checks nothing. Its own test
//! binary: answers are kept process-wide.
//!
//! The second and third tests call ashpd from a thread with no tokio runtime,
//! as GPUI's executor would: ashpd runs on zbus's `async-io`, whichever thread
//! built its connection (the third lets a tokio caller build it first;
//! docs/design/gpui-spikes.md, "Dependencies").
#![cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
@@ -11,6 +18,9 @@ use std::sync::atomic::{AtomicU32, Ordering};
use voelin_platform::proxy::proxy_for;
/// Set for the run on the bus of its own.
const ON_ITS_OWN_BUS: &str = "VOELIN_PROXY_TEST_ON_ITS_OWN_BUS";
/// What the GNOME portal answers: a SOCKS proxy for one host, none for the
/// others.
struct Resolver {
@@ -34,10 +44,72 @@ impl Resolver {
}
}
/// The configuration of the bus of its own: a session bus without the service
/// directories, so that nothing on it can be started by name. Its socket is
/// made in `dir`.
fn bus_config(dir: &std::path::Path) -> String {
format!(
r#"<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<busconfig>
<type>session</type>
<listen>unix:tmpdir={}</listen>
<auth>EXTERNAL</auth>
<policy context="default">
<allow send_destination="*" eavesdrop="true"/>
<allow eavesdrop="true"/>
<allow own="*"/>
</policy>
</busconfig>
"#,
dir.display()
)
}
/// Run the test `name` again under `dbus-run-session` on a bus of its own, and
/// say nothing was checked when that bus cannot be had.
fn on_a_bus_of_its_own(name: &str) {
let dir = std::env::temp_dir();
let config = dir.join(format!("voelin-proxy-test-bus-{}-{name}.conf", std::process::id()));
std::fs::write(&config, bus_config(&dir)).unwrap();
let run = std::process::Command::new("dbus-run-session")
.arg(format!("--config-file={}", config.display()))
.arg("--")
.arg(std::env::current_exe().unwrap())
.args(["--exact", name, "--nocapture", "--test-threads=1"])
.env(ON_ITS_OWN_BUS, "1")
.output();
let _ = std::fs::remove_file(&config);
let run = match run {
Ok(run) => run,
Err(e) => {
eprintln!("skipped, nothing was checked: dbus-run-session cannot be run ({e})");
return;
}
};
let text =
format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
if run.status.success() {
// A child that ran no test (its filter matched nothing) exits 0 as well.
assert!(
text.contains("test result: ok. 1 passed;"),
"the run on its own bus exited 0 without reporting `1 passed`:\n{text}"
);
return;
}
// The test ran and failed, or the bus never came up.
assert!(
!text.contains("running 1 test"),
"the test failed on its own bus ({}):\n{text}",
run.status
);
eprintln!("skipped, nothing was checked: no bus of its own could be started:\n{text}");
}
#[tokio::test]
async fn the_portal_names_the_proxy() {
if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_none() {
eprintln!("no session bus: run under dbus-run-session");
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
on_a_bus_of_its_own("the_portal_names_the_proxy");
return;
}
let lookups = Arc::new(AtomicU32::new(0));
@@ -66,3 +138,96 @@ async fn the_portal_names_the_proxy() {
assert_eq!(proxy_for("https://capped.example:8443/").await, None);
assert_eq!(lookups.load(Ordering::SeqCst), 2);
}
/// Run `future` on the calling thread, which parks while it waits: an executor
/// of no runtime at all, as a GPUI foreground task is to ashpd.
fn block_on<F: std::future::Future>(future: F) -> F::Output {
struct Unpark(std::thread::Thread);
impl std::task::Wake for Unpark {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
let waker = std::task::Waker::from(Arc::new(Unpark(std::thread::current())));
let mut cx = std::task::Context::from_waker(&waker);
let mut future = std::pin::pin!(future);
loop {
if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut cx) {
return output;
}
std::thread::park();
}
}
/// The stand-in portal on the bus of its own, served from the calling task.
async fn stand_in_portal(lookups: &Arc<AtomicU32>) -> zbus::Connection {
zbus::connection::Builder::session()
.unwrap()
.name("org.freedesktop.portal.Desktop")
.unwrap()
.serve_at("/org/freedesktop/portal/desktop", Resolver { lookups: lookups.clone() })
.unwrap()
.build()
.await
.unwrap()
}
/// A lookup through ashpd, from the calling task.
async fn lookup() -> Vec<ashpd::Uri> {
let resolver = ashpd::desktop::proxy_resolver::ProxyResolver::new().await.unwrap();
let uri = ashpd::Uri::parse("https://capped.example/").unwrap();
resolver.lookup(&uri).await.unwrap()
}
/// A lookup through ashpd from a thread of its own with no runtime, blocking
/// the caller's task for it (the pool's threads, `spawn_blocking`, have the
/// runtime in reach). The stand-in portal runs on the test's runtime: keep it
/// free while waiting.
async fn lookup_without_a_runtime() -> Vec<String> {
let caller = std::thread::spawn(|| {
assert!(tokio::runtime::Handle::try_current().is_err(), "this thread has no runtime");
block_on(lookup()).iter().map(|uri| uri.as_str().to_owned()).collect::<Vec<_>>()
});
tokio::task::spawn_blocking(move || caller.join().unwrap()).await.unwrap()
}
/// ashpd with `async-io`: a caller outside any tokio runtime gets its answer,
/// the connection's I/O running on zbus's own thread.
#[tokio::test(flavor = "multi_thread")]
async fn the_portal_answers_a_caller_without_a_runtime() {
const TEST: &str = "the_portal_answers_a_caller_without_a_runtime";
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
on_a_bus_of_its_own(TEST);
return;
}
let lookups = Arc::new(AtomicU32::new(0));
let _portal = stand_in_portal(&lookups).await;
assert_eq!(lookup_without_a_runtime().await, ["socks://127.0.0.1:2080"]);
assert_eq!(lookups.load(Ordering::SeqCst), 1);
}
/// ashpd keeps one session connection for the process, and zbus picks the
/// executor of a connection once, when it builds it: tokio if a tokio runtime
/// is current on that thread and zbus has its `tokio` feature on, its own
/// `async-io` thread otherwise. If the engine's runtime made the connection
/// first, a later caller with no runtime (a GPUI foreground task) would find a
/// tokio connection with no reactor to run on and panic ("there is no reactor
/// running" in zbus's property cache). With zbus on `async-io` alone in every
/// binary (notify-rust without `z-with-tokio`, no zbus `tokio` here either)
/// the order does not matter.
#[tokio::test(flavor = "multi_thread")]
async fn the_portal_answers_a_caller_without_a_runtime_after_a_tokio_caller() {
const TEST: &str = "the_portal_answers_a_caller_without_a_runtime_after_a_tokio_caller";
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
on_a_bus_of_its_own(TEST);
return;
}
let lookups = Arc::new(AtomicU32::new(0));
let _portal = stand_in_portal(&lookups).await;
// The tokio caller first: it builds the process's session connection.
let answer: Vec<_> = lookup().await.iter().map(|uri| uri.as_str().to_owned()).collect();
assert_eq!(answer, ["socks://127.0.0.1:2080"]);
// Then the caller with no runtime, on the same connection.
assert_eq!(lookup_without_a_runtime().await, ["socks://127.0.0.1:2080"]);
assert_eq!(lookups.load(Ordering::SeqCst), 2);
}
+123 -38
View File
@@ -35,44 +35,119 @@
//! the trait's [`KeyStore::sign_out`] starts with it and then reads the account
//! record and the device key with [`KeyStore::get`]: one damaged row, the
//! record's own included, would otherwise keep a sign-out from ever finishing,
//! and with it the deletion of the key the user asked to forget. Unbound is the
//! reading that never deletes on a guess: a sign-out neither deletes such a row
//! as a synced copy nor writes it, it stays as it is until a `put` of it writes
//! four good binding columns. A `data` column that is not text (a BLOB, or text
//! of bytes that are no UTF-8) is read as text with the odd bytes replaced, so
//! that a record that cannot be read is deleted by the sign-out, as the trait
//! says, instead of its read failing. A [`KeyStore::put`] of the text that
//! and with it the deletion of the synced copies and of the record, and the
//! forgetting of the key the user asked to forget. Unbound is the reading that
//! never deletes on a guess: a sign-out neither deletes such a row as a synced
//! copy nor writes it, it stays as it is until a `put` of it writes four good
//! binding columns. A `data` column that is not text (a BLOB, or text of bytes
//! that are no UTF-8) is read as text with the odd bytes replaced, so that a
//! record that cannot be read is deleted by the sign-out, as the trait says,
//! instead of its read failing. A [`KeyStore::put`] of the text that
//! [`KeyStore::get`] returned for such a row is taken for the data that is
//! there: it changes the binding and keeps the stored bytes, where any other
//! text replaces them (a TeamSpeak blob still has to be an identity). A row
//! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it
//! out with a warning.
//!
//! # Signing out keeps every key
//!
//! [`KeyStore::sign_out`] is the trait's own, run on this table, and since
//! Phase 2 task 34 of the protocol repository (open question 10 of its accounts
//! design, answered by the owner on 2026-10-24) it keeps every key of the
//! device. The device key stays, unbound and byte for byte, whether it was in
//! use before the account existed or the client made it for the account:
//! `AccountRecord::bound_existing_key` only records which, for the client's
//! wording, and no rule reads it. At every host without accounts that the user
//! reached with it, either key is the user's identity, and deleting it would
//! lose their servers, roles and memberships there. The identities that only
//! this device holds (a TeamSpeak identity of custody `DEVICE`, one the user
//! kept local) are unbound and kept as well.
//!
//! What a sign-out deletes is not a key of the device: the synced copies of
//! integration secrets, which the account service holds and every device can
//! fetch again (a copy of a TeamSpeak identity is a private key, and is deleted
//! like one, see below), and the account record, which holds no secret. A
//! sign-out does not release the device key at the account service either: the
//! key stays registered with the account there. The release is its own
//! operation, see below.
//!
//! # Releasing a device key
//!
//! The release of the device key from its account (part 2 of open question 10)
//! is the account service's operation followed by a local unbind, and the unbind
//! is a sign-out: `AccountClient::release` of `voelin-account-client` calls
//! `POST /v1/devices/<own>/release` after a password check, and then runs
//! [`KeyStore::sign_out`] with [`DeviceKeyChoice::Auto`], which keeps the key,
//! unbound. So the store needs nothing of its own for it: no call that unbinds
//! one key (a [`KeyStore::put`] of the blob without its binding does that, and
//! keeps the data, as the sign-out does), and no record that the key was
//! released. The accounts design asks the client to remember nothing of the
//! kind: the service holds the registration of the key (after a release it is
//! registered with no account, after a sign-out with the account that was
//! signed out of), and the client learns which at the next sign-in or sign-up,
//! from the service's answer (`CONFLICT`, field `device`), not from a note kept
//! here. The deletion of the account (`AccountClient::delete_account`) is the
//! same: the service writes a DEVICE and a RELEASED entry for every device key
//! of the account, and the local half is this sign-out, which keeps this
//! device's key.
//!
//! # Forgetting the device's identity
//!
//! "Forget this device's identity" is the user's explicit choice and the only
//! deletion of a key of the device; the UI offers to export the key first and
//! asks before it deletes.
//!
//! - Signed in, it is a sign-out with [`DeviceKeyChoice::Forget`] and the uid of
//! the device key. The caller names the key, because the key goes before the
//! record is read: a record that cannot be read does not keep it.
//! - Signed out, or with a key that no account ever bound, it is
//! [`KeyStore::remove`] of `(KIND_VOELIN, uid)`; a TeamSpeak identity is
//! [`Store::delete_identity`]. Neither looks at an account record, so a UI
//! that forgets the device key of the account it is signed in to does it
//! through the sign-out, not through `remove`.
//!
//! The store has no call that exports, because it would only wrap what the
//! caller can read before it deletes: a Voelin key is
//! `KeyStore::voelin_key(uid)` followed by `IdentityKey::to_pkcs8` (the DER that
//! `voelin_identity::FileSigner` reads back; the buffer is zeroized when it is
//! dropped), and a TeamSpeak identity is `Store::identity(id)` followed by
//! `voelin_core::ts::identity::export` or `write_export`. The same two calls,
//! with [`KeyStore::list`] for the `voelin` rows, serve the dialog that deletes
//! the account: it offers an export of the device keys before the service is
//! asked.
//!
//! # Deleted keys leave no trace
//!
//! The rows are private keys, so a removed row is not left behind in the file:
//! every connection sets `secure_delete`, which makes SQLite overwrite what it
//! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as
//! [`Store::delete_identity`] does, so that the frame of the log that held the
//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with
//! `remove`, truncates the log once, after its last step, not after each
//! removal. The checkpoint waits for another connection for a moment at most
//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it,
//! and then the removal still succeeds and a warning says that the deleted
//! bytes may stay in the log file, until a later checkpoint truncates the log,
//! later writes overwrite those frames, or the last connection to the database
//! closes and the log is deleted.
//! page with the key is gone too. A forgotten key needs exactly that. So does
//! the one deletion a sign-out still makes of a key: a synced copy of a
//! TeamSpeak identity, and with `Forget` the device key itself. The sign-out
//! deletes with `remove` on a `SignOutPass` and truncates the log once, after
//! its last step, not after each removal; one that deletes nothing (the record
//! was gone, no copies) truncates nothing. The checkpoint waits for another
//! connection for a moment at most (`Store::truncate_wal`): one that keeps
//! reading an old snapshot blocks it, and then the removal still succeeds and a
//! warning says that the deleted bytes may stay in the log file, until a later
//! checkpoint truncates the log, later writes overwrite those frames, or the
//! last connection to the database closes and the log is deleted.
//!
//! The device key is never a synced copy. The account record names the Voelin key
//! that is the installation's device key, and [`KeyStore::sign_out`] deletes
//! every identity bound with `synced = true` in its first step, before it reads
//! the record, so a key stored that way would be deleted whatever the record
//! says (a key that predates the account is to be kept). The store therefore
//! refuses, with an error that says why, a [`KeyStore::put`] of a `voelin` blob
//! with `synced = true` while an account record names its uid as the device, or
//! while a record cannot be read, because then it cannot tell; and a put of an
//! # The device key is never a synced copy
//!
//! A sign-out keeps the device key, but its first step deletes every identity
//! bound with `synced = true`, before it reads the account record that names
//! the device key. A device key stored that way would be deleted by that step,
//! whether it predates the account or not, which is what the rule that a
//! sign-out keeps every device key forbids. The store therefore refuses, with an
//! error that says why, a [`KeyStore::put`] of a `voelin` blob with
//! `synced = true` while an account record names its uid as the device, or while
//! a record cannot be read, because then it cannot tell; and a put of an
//! account record that names a key which is stored as a synced copy. A binding
//! with `synced = false` is accepted: a sign-out unbinds such a key and then
//! follows the record. The check and the write are done under the store's lock;
//! a second process writing the same file at the same moment is not covered.
//! with `synced = false` is accepted: a sign-out unbinds such a key and keeps
//! it. The check and the write are done under the store's lock; a second
//! process writing the same file at the same moment is not covered.
//!
//! A TeamSpeak blob that is refused says why in words that carry none of its
//! input: its `data` is the identity's private key, and an error reaches log
@@ -136,8 +211,10 @@ const PUT: &str = "INSERT INTO identities
/// access to the TeamSpeak methods of the same connection.
///
/// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as
/// `voelin-identity` defines them, on top of the five methods here; the
/// sign-out only truncates the write-ahead log once, at its end.
/// `voelin-identity` defines them, on top of the five methods here: a sign-out
/// keeps every key of the device (only [`DeviceKeyChoice::Forget`] deletes the
/// device key), and only truncates the write-ahead log once, at its end, when
/// it deleted something.
pub struct SqliteKeyStore {
store: Mutex<Store>,
}
@@ -270,10 +347,13 @@ impl KeyStore for SqliteKeyStore {
/// The trait's sign-out, with the log truncated once after its last step
/// instead of after each of its removals: it removes up to a handful of
/// rows, and a checkpoint that another connection blocks costs a moment
/// rows (the synced copies, the account record and, with
/// [`DeviceKeyChoice::Forget`], the device key; every other key stays), and
/// a checkpoint that another connection blocks costs a moment
/// (`Store::truncate_wal`) each time. The steps are the trait's own; they
/// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves
/// the checkpoint to this method.
/// the checkpoint to this method. A sign-out that deleted nothing does not
/// checkpoint.
fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult<SignOut> {
let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) };
let outcome = KeyStore::sign_out(&pass, account, device_key);
@@ -299,7 +379,10 @@ fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult<bool> {
/// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same
/// rows, but `remove` only notes that it deleted something, so that the sign-out
/// truncates the log once at its end.
/// truncates the log once at its end. What a sign-out removes is the synced
/// copies of integration secrets, the account record and, when the user chose
/// to forget it, the device key; unbinding goes through `put`, which deletes
/// nothing.
struct SignOutPass<'a> {
store: &'a SqliteKeyStore,
/// Whether a row was deleted.
@@ -470,26 +553,28 @@ enum Refused {
/// `uid` is unique across kinds in this table.
#[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")]
UidHeld { uid: String, kind: String },
/// The Voelin key is the device key of an account record. A sign-out
/// deletes a synced copy without reading the record, so the key the record
/// says to keep would be deleted.
/// The Voelin key is the device key of an account record. A sign-out keeps
/// the device key, but it deletes a synced copy without reading the record,
/// so a device key stored as one would be deleted all the same.
#[error(
"the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \
stored as a synced copy (synced = true): a sign-out would delete it whatever the record says"
stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \
reads the record, so it would delete the device key that it keeps"
)]
SyncedDeviceKey { uid: String, record: String },
/// An account record cannot be read, so the store cannot tell whether the
/// Voelin key is its device key.
#[error(
"the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \
record {record:?} cannot be read, so it may name this key as the device key"
record {record:?} cannot be read, so it may name this key as the device key, which a \
sign-out keeps but would delete as a synced copy"
)]
UnreadableRecord { uid: String, record: String },
/// The device key of the record is stored as a synced copy already.
#[error(
"the account record {record:?} names the Voelin key {device:?} as the device key, which is \
stored as a synced copy (synced = true): a sign-out would delete it whatever the record \
says"
stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \
reads the record, so it would delete the device key that it keeps"
)]
RecordNamesSyncedKey { record: String, device: String },
}
+36
View File
@@ -33,12 +33,48 @@ pub use store::{
Bookmark, CachedServerIcon, IdentityEntry, IdentityOrigin, QueryConfig, QueryTransport, Store,
};
/// How the JSON of a stored TeamSpeak identity is wrong: the category of the
/// reader's complaint and nothing of the text, which holds a private key.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IdentityDamage {
/// The text is not JSON.
Malformed,
/// The text ends before the JSON does.
CutShort,
/// The JSON is not that of an identity: a field is missing or of another
/// type, or the key does not import.
NotAnIdentity,
/// The text could not be read.
Unreadable,
}
impl std::fmt::Display for IdentityDamage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Malformed => "malformed",
Self::CutShort => "cut short",
Self::NotAnIdentity => "not an identity",
Self::Unreadable => "unreadable",
})
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("database: {0}")]
Db(#[from] rusqlite::Error),
#[error("serialization: {0}")]
Json(#[from] serde_json::Error),
/// The JSON of a stored TeamSpeak identity cannot be read, which only damage
/// outside the client can cause. It says how the text is wrong and where, and
/// never what it holds: the text is a private key, and the message of the
/// JSON reader quotes the value it refuses (`tsproto` reports a key that does
/// not import as an invalid value, the key string and all), so that message is
/// not kept, not here and not in a log line.
#[error(
"the stored TeamSpeak identity cannot be read: {damage} at line {line}, column {column}"
)]
Identity { damage: IdentityDamage, line: usize, column: usize },
#[error("{0} {1} not found")]
NotFound(&'static str, i64),
#[error("secret store: {0}")]
+54 -12
View File
@@ -8,7 +8,7 @@ use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use tsclientlib::Identity;
use crate::{Error, Result};
use crate::{Error, IdentityDamage, Result};
/// A schema migration: SQL, or code for what SQL alone cannot do.
enum Migration {
@@ -98,7 +98,7 @@ pub enum IdentityOrigin {
/// Made by the app on its own because it had none; nobody chose it, so
/// the official client's identity may take its place as the default.
Created,
/// From another client (`voelin_core::identity`).
/// From another client (`voelin_core::ts::identity`).
Imported,
/// Made or chosen as the default by the user.
User,
@@ -244,6 +244,28 @@ impl Bookmark {
/// waits.
const CHECKPOINT_WAIT: Duration = Duration::from_millis(150);
/// The TeamSpeak identity in the JSON of a stored row.
///
/// A text that does not read (it could only have been damaged outside the
/// client: [`Store::add_identity`] writes what `serde_json` makes of an
/// identity) is refused with [`Error::Identity`], which says how it is wrong and
/// where and never what it holds, as `voelin-core`'s `ts::identity::from_json`
/// does for the text it is handed. The reader's own message is dropped: it
/// quotes a value it refuses, and `tsproto` reports a key that does not import
/// as an invalid value, the key string and all, which would reach a status line
/// or a log.
fn identity_from_json(json: &str) -> Result<Identity> {
serde_json::from_str(json).map_err(|error| {
let damage = match error.classify() {
serde_json::error::Category::Syntax => IdentityDamage::Malformed,
serde_json::error::Category::Eof => IdentityDamage::CutShort,
serde_json::error::Category::Data => IdentityDamage::NotAnIdentity,
serde_json::error::Category::Io => IdentityDamage::Unreadable,
};
Error::Identity { damage, line: error.line(), column: error.column() }
})
}
pub struct Store {
pub(crate) db: Connection,
}
@@ -348,7 +370,7 @@ impl Store {
})?;
rows.map(|row| {
let (id, name, uid, data, origin, is_default) = row?;
let identity: Identity = serde_json::from_str(&data)?;
let identity = identity_from_json(&data)?;
let origin = IdentityOrigin::parse(&origin);
Ok(IdentityEntry { id, name, uid, level: identity.level(), origin, is_default })
})
@@ -395,7 +417,7 @@ impl Store {
)
.optional()?;
let data = data.ok_or(Error::NotFound("identity", id))?;
Ok(serde_json::from_str(&data)?)
identity_from_json(&data)
}
/// Store an identity again, e.g. after its security level was improved.
@@ -630,23 +652,43 @@ mod tests {
reader.query_row("SELECT count(*) FROM identities", [], |r| r.get::<_, i64>(0)).unwrap();
store.add_identity("second", &Identity::create(), IdentityOrigin::User).unwrap();
// A value that is not the default, so that restoring a constant would show.
// A value that is not the default, so that restoring a constant would
// show, and one so long that a checkpoint that waited as long as the
// connection allows would not come back by itself.
const HOUR_MS: i64 = 3_600_000;
let timeout = |store: &Store| -> i64 {
store.db.pragma_query_value(None, "busy_timeout", |r| r.get(0)).unwrap()
};
store.db.busy_timeout(Duration::from_millis(2345)).unwrap();
let started = std::time::Instant::now();
store.truncate_wal();
let elapsed = started.elapsed();
assert!(elapsed < Duration::from_secs(1), "the checkpoint waited {elapsed:?}");
store.db.busy_timeout(Duration::from_secs(3600)).unwrap();
// "Briefly" is not a time: a checkpoint ends in two fsyncs, which take
// seconds under disk pressure (it took 6 s here beside `dd conv=fsync`
// loops), and only a checkpoint that comes back while the reader still
// holds its snapshot has not waited for it. So the reader lets go from
// another thread after 30 s, which ends a checkpoint that does not give
// up with a failure here and not with an hour's wait.
let (back, hear) = std::sync::mpsc::channel::<()>();
let watchdog = std::thread::spawn(move || {
let in_time = hear.recv_timeout(Duration::from_secs(30)).is_ok();
if !in_time {
reader.execute_batch("COMMIT").unwrap();
}
(reader, in_time)
});
// One attempt, which the reader blocks (`1`).
let blocked = store.checkpoint_truncate();
back.send(()).ok();
let (reader, in_time) = watchdog.join().unwrap();
assert!(in_time, "the checkpoint waited for the reader instead of giving up");
assert_eq!(blocked.unwrap(), 1, "the reader should block the reset");
assert!(std::fs::metadata(&wal).unwrap().len() > 0, "the reader should block the reset");
assert_eq!(timeout(&store), 2345);
assert_eq!(timeout(&store), HOUR_MS);
// Without the reader the same call resets the log.
reader.execute_batch("COMMIT").unwrap();
store.truncate_wal();
assert_eq!(std::fs::metadata(&wal).unwrap().len(), 0);
assert_eq!(timeout(&store), 2345);
assert_eq!(timeout(&store), HOUR_MS);
drop(reader);
drop(store);
std::fs::remove_dir_all(dir).unwrap();
+330
View File
@@ -0,0 +1,330 @@
//! A damaged identity row: what the store returns and logs about it says how
//! the row is wrong and never what it holds.
//!
//! The `data` of a TeamSpeak row is the JSON of a private key. Only something
//! outside the client can damage it, but when that happens the error of the
//! JSON reader quotes the value it refuses (`tsproto` reports a key that does
//! not import as an invalid value, the key string and all), and an error
//! reaches a status line, an event or a log. `Store::identity` and
//! `Store::identities` used to return that error as it was.
//!
//! Every case here damages a row of a database file through a second
//! connection, calls everything of the store that reads or writes the row, and
//! looks through the errors (their text, their `Debug` text and their sources)
//! and the logs at TRACE for any 8 characters in a row of what the row held.
use rusqlite::types::Value;
use rusqlite::{Connection, params};
use tsclientlib::Identity;
use voelin_identity::{
AccountBinding, AccountId, DeviceKeyChoice, IdentityBlob, IntegrationId, KIND_TEAMSPEAK,
KeyStore, Uid, account_uid,
};
use voelin_store::{Error, IdentityDamage, IdentityOrigin, SqliteKeyStore, Store};
mod support;
/// A directory of its own that is removed again.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new(name: &str) -> Self {
let dir = std::env::temp_dir()
.join(format!("voelin-identity-text-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
fn db(&self) -> std::path::PathBuf {
self.0.join("client.db")
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Letters and digits that no message of this crate, of `serde_json` or of
/// SQLite is made of in a run of eight.
const SECRET: &str = "Zq7Xm2Vb9Lk4Pw8Rt3Yn6Hd1Fs5Jc0Ga";
const OTHER_SECRET: &str = "Qx3Wv8Nb5Mj1Kh6Gf2Dt9Rs4Pl7Yc0Za";
/// The JSON of a fresh identity whose key lost its last two characters (a key
/// that does not import), and that cut key.
fn json_with_a_cut_key() -> (String, String) {
let mut json = serde_json::to_value(Identity::create()).unwrap();
let key = json["key"].as_str().unwrap().to_owned();
let cut = key[..key.len() - 2].to_owned();
json["key"] = cut.clone().into();
(json.to_string(), cut)
}
/// The JSON of a fresh identity whose counter is a string (`SECRET`), and that
/// string: the reader quotes it in its message.
fn json_with_a_counter_of_the_wrong_type() -> String {
let mut json = serde_json::to_value(Identity::create()).unwrap();
json["counter"] = SECRET.into();
json.to_string()
}
/// The JSON of a fresh identity cut in the middle of its key, and the key.
fn json_cut_inside_its_key() -> (String, String) {
let json = serde_json::to_value(Identity::create()).unwrap();
let key = json["key"].as_str().unwrap().to_owned();
let text = json.to_string();
let cut = text.find(&key).unwrap() + key.len() / 2;
(text[..cut].to_owned(), key)
}
/// How a row's `data` is damaged: what is stored, as which storage class, and
/// the text of it that must never be repeated.
struct Damage {
label: &'static str,
value: Value,
/// `CAST(? AS TEXT)`: the bytes are stored as TEXT, not as a BLOB.
as_text: bool,
secret: String,
/// What the store says of it, when it reads it as JSON.
damage: Option<IdentityDamage>,
}
fn damages() -> Vec<Damage> {
let (cut, cut_key) = json_with_a_cut_key();
let (cut_short, whole_key) = json_cut_inside_its_key();
let mut not_utf8 = format!(r#"{{"key":"{SECRET}","counter":1}}"#).into_bytes();
not_utf8.push(0xff);
vec![
Damage {
label: "a key that does not import",
value: Value::Text(cut),
as_text: false,
secret: cut_key,
damage: Some(IdentityDamage::NotAnIdentity),
},
Damage {
label: "a field of the wrong type",
value: Value::Text(json_with_a_counter_of_the_wrong_type()),
as_text: false,
secret: SECRET.to_owned(),
damage: Some(IdentityDamage::NotAnIdentity),
},
Damage {
label: "syntax",
value: Value::Text(format!("not json: {SECRET}")),
as_text: false,
secret: SECRET.to_owned(),
damage: Some(IdentityDamage::Malformed),
},
Damage {
label: "cut short",
value: Value::Text(cut_short),
as_text: false,
secret: whole_key,
damage: Some(IdentityDamage::CutShort),
},
Damage {
label: "bytes that are no UTF-8, stored as a BLOB",
value: Value::Blob(not_utf8.clone()),
as_text: false,
secret: SECRET.to_owned(),
damage: None,
},
Damage {
label: "bytes that are no UTF-8, stored as TEXT",
value: Value::Blob(not_utf8),
as_text: true,
secret: SECRET.to_owned(),
damage: None,
},
]
}
/// Fail if `text` holds any 8 characters in a row of `secret`.
fn assert_holds_no_piece_of(text: &str, secret: &str, what: &str) {
assert!(secret.len() >= 8 && secret.is_ascii());
for piece in secret.as_bytes().windows(8) {
let piece = std::str::from_utf8(piece).unwrap();
assert!(!text.contains(piece), "{what}: {text:?} holds {piece:?} of the row's data");
}
}
/// The texts an error shows to a caller: how it reads, its `Debug` text and
/// those of everything it was caused by.
fn texts_of(error: &(dyn std::error::Error + 'static)) -> Vec<String> {
let mut texts = vec![error.to_string(), format!("{error:?}")];
let mut source = error.source();
while let Some(cause) = source {
texts.push(cause.to_string());
texts.push(format!("{cause:?}"));
source = cause.source();
}
texts
}
fn binding() -> AccountBinding {
let account = account_uid(&Uid::from_bytes([1; 32]), &AccountId::from_bytes([2; 16]));
AccountBinding {
account,
integration: Some(IntegrationId::from_bytes([7; 16])),
rev: 3,
synced: false,
}
}
/// A database file with one TeamSpeak identity, its `data` replaced by `damage`
/// through a second connection. Returns the id and uid of the row.
fn damaged_database(scratch: &Scratch, damage: &Damage) -> (i64, String) {
let store = Store::open(&scratch.db()).unwrap();
let identity = Identity::create();
let id = store.add_identity("damaged", &identity, IdentityOrigin::User).unwrap();
let uid = identity.key().to_pub().get_uid();
drop(store);
let db = Connection::open(scratch.db()).unwrap();
let sql = if damage.as_text {
"UPDATE identities SET data = CAST(?1 AS TEXT) WHERE id = ?2"
} else {
"UPDATE identities SET data = ?1 WHERE id = ?2"
};
assert_eq!(db.execute(sql, params![damage.value, id]).unwrap(), 1);
(id, uid)
}
#[test]
fn the_json_readers_own_message_quotes_what_it_refuses() {
// Without this the cases below could not fail: serde's message for a key
// that does not import and for a field of the wrong type repeats the value.
let (json, cut_key) = json_with_a_cut_key();
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
assert!(raw.contains(&cut_key), "the reader's own message quotes the key: {raw}");
let typed = json_with_a_counter_of_the_wrong_type();
let raw = serde_json::from_str::<Identity>(&typed).unwrap_err().to_string();
assert!(raw.contains(SECRET), "the reader's own message quotes the value: {raw}");
}
#[test]
fn a_damaged_identity_row_is_reported_by_its_kind_of_damage_and_never_by_its_text() {
for damage in damages() {
let scratch = Scratch::new("store");
let (id, _) = damaged_database(&scratch, &damage);
let label = damage.label;
let store = Store::open(&scratch.db()).unwrap();
let ((one, all, default), lines) = support::at_trace(|| {
(
store.identity(id).unwrap_err(),
store.identities().unwrap_err(),
store.default_identity().unwrap_err(),
)
});
for (call, error) in [("identity", &one), ("identities", &all), ("default", &default)] {
for text in texts_of(error) {
assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: {call}"));
}
if let Some(expected) = damage.damage {
// The kind of damage and where, in the store's own words.
match error {
Error::Identity { damage, line, column } => {
assert_eq!(*damage, expected, "{label}: {call}");
assert_eq!((*line, *column > 0), (1, true), "{label}: {call}: {error}");
let shown = error.to_string();
assert!(
shown.starts_with(&format!(
"the stored TeamSpeak identity cannot be read: {expected} at line 1, column "
)),
"{label}: {call}: {shown}"
);
}
other => panic!("{label}: {call}: {other:?}"),
}
}
}
for line in &lines {
assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line"));
}
}
}
#[test]
fn a_damaged_identity_row_does_not_leak_through_the_key_store_either() {
for damage in damages() {
let scratch = Scratch::new("keystore");
let (_id, uid) = damaged_database(&scratch, &damage);
let label = damage.label;
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
// Everything that reads or writes the row, in the order a sign-out would,
// with the errors and the logs of all of it kept.
let (results, lines) = support::at_trace(|| {
let mut errors: Vec<Box<dyn std::error::Error + Send + Sync>> = Vec::new();
let mut note = |result: Result<(), voelin_identity::KeyStoreError>| {
if let Err(error) = result {
errors.push(Box::new(error));
}
};
let listed = store.list().unwrap();
let entry = listed.iter().find(|info| info.uid == uid).expect("the row is listed");
assert_eq!(entry.level, 0, "{label}: damage reads as level 0");
// What `get` hands out is the data itself; a `put` of it rebinds the row.
let blob = store.get(KIND_TEAMSPEAK, &uid).unwrap().expect("the row is read");
note(store.put(&blob.clone().with_binding(binding())));
// Other data over the row is checked and refused, and the refusal does
// not repeat it.
let other = format!(r#"{{"key":"{SECRET}","counter":"{OTHER_SECRET}"}}"#);
note(store.put(&IdentityBlob::from_row(KIND_TEAMSPEAK, uid.clone(), 0, other)));
note(store.put(&IdentityBlob::teamspeak(uid.clone(), 8, SECRET)));
// The sign-out that unbinds it, and the delete that removes it.
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
store.remove(KIND_TEAMSPEAK, &uid).unwrap();
errors
});
assert_eq!(results.len(), 2, "{label}: the two refusals: {results:?}");
for error in &results {
for text in texts_of(error.as_ref()) {
assert_holds_no_piece_of(&text, &damage.secret, &format!("{label}: a refusal"));
assert_holds_no_piece_of(
&text,
SECRET,
&format!("{label}: a refusal of other data"),
);
assert_holds_no_piece_of(&text, OTHER_SECRET, &format!("{label}: other data"));
}
}
for line in &lines {
assert_holds_no_piece_of(line, &damage.secret, &format!("{label}: a log line"));
assert_holds_no_piece_of(line, SECRET, &format!("{label}: a log line, other data"));
}
}
}
#[test]
fn the_capture_sees_what_the_store_logs() {
// A control for the cases above: a row whose binding columns are damaged is
// listed with a warning that names it, and the capture takes it in at TRACE.
let scratch = Scratch::new("control");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let blob = IdentityBlob::new("future", "future:one", 0, format!(r#"{{"secret":"{SECRET}"}}"#));
store.put(&blob).unwrap();
let db = Connection::open(scratch.db()).unwrap();
assert_eq!(
db.execute("UPDATE identities SET synced = 2 WHERE kind = 'future'", []).unwrap(),
1
);
let (listed, lines) = support::at_trace(|| store.list().unwrap());
assert_eq!(listed.len(), 1);
let warning = lines
.iter()
.find(|line| line.contains("the binding columns of an identity cannot be read"))
.unwrap_or_else(|| panic!("no warning in {lines:?}"));
assert!(warning.starts_with("WARN "), "{warning}");
assert!(warning.contains("future:one"), "{warning}");
// And it does not carry the row's data either.
for line in &lines {
assert_holds_no_piece_of(line, SECRET, "a log line");
}
}
+371 -71
View File
@@ -31,6 +31,8 @@ use voelin_identity::{
};
use voelin_store::{IdentityOrigin, SqliteKeyStore, Store};
mod support;
/// What `serde_json::to_string(&tsproto::Identity)` writes for the test
/// identity of tsproto's own `identity_tests`.
const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#;
@@ -803,8 +805,9 @@ fn the_record_fixture_is_what_the_protocol_writes() {
}
#[test]
fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
// The device key was made for the account: signing out deletes it.
fn signing_out_deletes_the_copies_and_keeps_the_keys_and_the_device_secrets() {
// The device key was made for the account: signing out keeps it all the
// same, unbound (open question 10 of the accounts design).
let Install { store, synced, device_only, local } = signed_in_install(false);
let mine = binding().account;
let theirs = account_uid(&issuer(), &AccountId::from_bytes([9; 16]));
@@ -815,19 +818,20 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
store.put_voelin_key(&other_key).unwrap();
let done = store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap();
let mut expected_removed = vec![
(KIND_ACCOUNT.to_owned(), record().blob_uid()),
pair(&synced),
(KIND_VOELIN.to_owned(), key().uid().to_base32()),
];
let mut expected_removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&synced)];
expected_removed.sort();
assert_eq!(sorted(done.removed.clone()), expected_removed, "{done:?}");
assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]);
assert_eq!(
sorted(done.unbound.clone()),
sorted(vec![device_key_info(), info_of(&device_only.clone().with_binding(None))]),
"{done:?}"
);
// What is left: the device secret unbound and byte for byte as it was, the
// local and the other account's identities as they were, the other key.
// What is left: the device key, the device secret unbound and byte for
// byte as it was, the local and the other account's identities as they
// were, the other key.
assert!(store.get(KIND_TEAMSPEAK, &synced.uid).unwrap().is_none());
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
assert_eq!(store.voelin_key(&key().uid()).unwrap().unwrap().uid(), key().uid());
assert_eq!(store.account_record().unwrap(), None);
let kept = store.get(KIND_TEAMSPEAK, &device_only.uid).unwrap().unwrap();
assert_eq!(kept, device_only.clone().with_binding(None));
@@ -835,11 +839,11 @@ fn signing_out_deletes_the_copies_and_keeps_the_device_secrets() {
assert_eq!(store.get(KIND_TEAMSPEAK, &local.uid).unwrap().unwrap(), local);
assert_eq!(store.get(KIND_TEAMSPEAK, &theirs_blob.uid).unwrap().unwrap(), theirs_blob);
assert!(store.voelin_key(&other_key.uid()).unwrap().is_some());
assert_eq!(store.list().unwrap().len(), 4);
assert_eq!(store.list().unwrap().len(), 5);
// Signing out again finds nothing to do.
assert_eq!(store.sign_out(&mine, DeviceKeyChoice::Auto).unwrap(), SignOut::default());
assert_eq!(store.list().unwrap().len(), 4);
assert_eq!(store.list().unwrap().len(), 5);
// Another account's sign-out acts on that account's identities only.
assert_eq!(
store.sign_out(&theirs, DeviceKeyChoice::Auto).unwrap().removed,
@@ -892,17 +896,38 @@ fn signing_out_keeps_a_device_key_that_predates_the_account() {
}
#[test]
fn signing_out_deletes_a_device_key_the_client_made_for_the_account() {
fn signing_out_keeps_a_device_key_the_client_made_for_the_account_too() {
// Open question 10 of the accounts design (answered 2026-10-24): a key that
// the client made for the account is the user's identity at every host
// without accounts that the user reached with it as well, so `Auto` keeps
// it like a key that predates the account. Only `Forget` deletes it.
let Install { store, device_only, local, .. } = signed_in_install(false);
let key_before = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
let signature = key().sign(b"the same key, signed before and after");
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.removed.contains(&device_key_info()), "{done:?}");
assert!(!done.unbound.contains(&device_key_info()), "{done:?}");
assert!(store.voelin_key(&key().uid()).unwrap().is_none());
assert!(!done.removed.contains(&device_key_info()), "{done:?}");
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays");
assert_eq!(kept.sign(b"the same key, signed before and after"), signature);
let key_after = store.get(KIND_VOELIN, &key().uid().to_base32()).unwrap().unwrap();
assert_eq!(key_after, key_before, "the stored blob is untouched");
assert_eq!(key_after.binding, None);
let mut left = sorted(store.list().unwrap());
left.sort();
let mut expected = vec![pair(&device_only), pair(&local)];
let mut expected = vec![pair(&device_only), pair(&local), pair(&key_after)];
expected.sort();
assert_eq!(left, expected, "the device secret and the local one");
assert_eq!(left, expected, "the key, the device secret and the local one");
// The flag changes nothing: a key that predates the account gets the same
// treatment. (The other identities of the two installs are fresh ones, so
// the reports differ in them.)
let existing = signed_in_install(true);
let again = existing.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(again.unbound.contains(&device_key_info()), "{again:?}");
assert!(!again.removed.contains(&device_key_info()), "{again:?}");
assert_eq!(again.removed.len(), done.removed.len());
assert_eq!(again.unbound.len(), done.unbound.len());
}
#[test]
@@ -1282,16 +1307,10 @@ impl OnFile {
/// What a sign-out of `choice` must have done, whatever else was damaged:
/// the record and the synced copy are gone, the device-only secret is
/// unbound and the local identity is as it was; the device key is deleted
/// when the user forgot it or the client made it for the account, and
/// reported as kept and unbound otherwise.
fn assert_signed_out(
&self,
done: &SignOut,
bound_existing_key: bool,
choice: DeviceKeyChoice,
label: &str,
) {
let key_goes = matches!(choice, DeviceKeyChoice::Forget(_)) || !bound_existing_key;
/// when the user forgot it, and reported as kept and unbound otherwise,
/// whether it predates the account or not.
fn assert_signed_out(&self, done: &SignOut, choice: DeviceKeyChoice, label: &str) {
let key_goes = matches!(choice, DeviceKeyChoice::Forget(_));
let mut removed = vec![(KIND_ACCOUNT.to_owned(), record().blob_uid()), pair(&self.synced)];
let mut unbound = vec![pair(&self.device_only)];
let device_key = (KIND_VOELIN.to_owned(), key().uid().to_base32());
@@ -1335,7 +1354,7 @@ const RECORD_ROW_DAMAGE: [&str; 5] = [
fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
// The record carries no binding, so damage in those columns says nothing
// about the record: it is read, and the sign-out does what it always does.
// `Forget` deletes the key it names; `Auto` follows the record.
// `Forget` deletes the key it names; `Auto` keeps it.
for bound_existing_key in [true, false] {
for damage in RECORD_ROW_DAMAGE {
for choice in [DeviceKeyChoice::Auto, DeviceKeyChoice::Forget(key().uid())] {
@@ -1346,7 +1365,7 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
.store
.sign_out(&binding().account, choice)
.unwrap_or_else(|error| panic!("{label}: {error}"));
install.assert_signed_out(&done, bound_existing_key, choice, &label);
install.assert_signed_out(&done, choice, &label);
}
}
}
@@ -1354,8 +1373,9 @@ fn a_damaged_account_record_row_does_not_keep_a_sign_out_from_finishing() {
#[test]
fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() {
// With `Auto` and a key that predates the account, the trait reads the key
// to report it as kept. Damage in its binding columns must not fail that.
// With `Auto` the trait reads the key to report it as kept, whether it
// predates the account or not. Damage in its binding columns must not fail
// that.
for bound_existing_key in [true, false] {
for damage in [
"UPDATE identities SET synced = 2 WHERE kind = 'voelin'",
@@ -1369,12 +1389,10 @@ fn a_damaged_device_key_row_does_not_keep_a_sign_out_from_finishing() {
.store
.sign_out(&binding().account, DeviceKeyChoice::Auto)
.unwrap_or_else(|error| panic!("{label}: {error}"));
install.assert_signed_out(&done, bound_existing_key, DeviceKeyChoice::Auto, &label);
if bound_existing_key {
// The key was kept, as it was stored.
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
}
install.assert_signed_out(&done, DeviceKeyChoice::Auto, &label);
// The key was kept, as it was stored.
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
}
}
}
@@ -1423,7 +1441,7 @@ fn an_account_row_whose_data_is_not_text_is_deleted_like_an_unreadable_record()
assert!(store.get(KIND_TEAMSPEAK, &install.synced.uid).unwrap().is_none(), "{label}");
let secret = store.get(KIND_TEAMSPEAK, &install.device_only.uid).unwrap().unwrap();
assert_eq!(secret.binding, None, "{label}");
// `Auto` cannot find the key the record named, and keeps it.
// `Auto` keeps the key, as it always does; `Forget` deleted it first.
let forgot = matches!(choice, DeviceKeyChoice::Forget(_));
assert_eq!(store.voelin_key(&key().uid()).unwrap().is_none(), forgot, "{label}");
assert_eq!(store.sign_out(&binding().account, choice).unwrap(), SignOut::default());
@@ -1623,14 +1641,13 @@ fn key_text(json: &str, field: &str) -> String {
}
#[test]
fn a_key_deleted_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() {
// The device key the client made for the account goes with `Auto`, and a
// key that predates the account goes when the user forgets it. Either way
// its PKCS#8 text, and a synced TeamSpeak copy's key, must not stay in the
// free pages of `client.db` or in a frame of `client.db-wal`.
for (bound_existing_key, choice) in
[(false, DeviceKeyChoice::Auto), (true, DeviceKeyChoice::Forget(key().uid()))]
{
fn a_key_forgotten_by_a_sign_out_is_in_neither_the_database_file_nor_its_log() {
// The device key goes when the user forgets it, whether it predates the
// account or the client made it for the account. Its PKCS#8 text, and a
// synced TeamSpeak copy's key, must not stay in the free pages of
// `client.db` or in a frame of `client.db-wal`.
for bound_existing_key in [true, false] {
let choice = DeviceKeyChoice::Forget(key().uid());
let scratch = Scratch::new("scrub-signout");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let device = IdentityBlob::voelin(&key()).unwrap();
@@ -1697,13 +1714,23 @@ fn removing_through_the_key_store_leaves_no_key_behind_either() {
}
#[test]
fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer() {
fn a_reader_that_blocks_the_checkpoint_costs_one_checkpoint_and_starves_no_writer() {
// A connection that keeps a read snapshot (a long query of the UI, a backup)
// keeps the checkpoint that truncates the log from finishing. The sign-out
// still deletes and warns that the bytes may stay in the log, and it waits
// for the checkpoint a moment, not for the busy timeout of five seconds once
// per removed row. While the checkpoint waits it holds the writer lock of the
// log, so a second connection that writes meanwhile must get through.
// still deletes and warns that the bytes may stay in the log, and it makes
// one checkpoint for all its removals, not one per removed row. While the
// checkpoint waits it holds the writer lock of the log, so a second
// connection that writes meanwhile must get through.
//
// No clock decides anything here. A checkpoint ends in two fsyncs, and under
// disk pressure (a build or a copy writing beside the tests) they take
// seconds: the review saw sign-outs of 1.2 to 1.9 s at 10 to 30 % I/O
// pressure, and `dd conv=fsync` loops beside 32 busy loops made them 5 s. A
// bound on the sign-out or a short busy timeout on the writer failed this
// test with "database is locked" for a checkpoint that was only slow. That a
// checkpoint gives up on a reader after a moment and does not wait out the
// connection's busy timeout is pinned where that timeout can be set to an
// hour: `store::tests::a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was`.
let scratch = Scratch::new("blocked-checkpoint");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
store.put_voelin_key(&key()).unwrap();
@@ -1718,37 +1745,71 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer(
let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 4);
/// Stops the writer when dropped, so that a failed assertion of the test does
/// not leave the scope waiting for it.
struct StopsTheWriter<'a>(&'a AtomicBool);
impl Drop for StopsTheWriter<'_> {
fn drop(&mut self) {
self.0.store(true, Ordering::Relaxed);
}
}
let stop = AtomicBool::new(false);
let (done, elapsed, writes, errors) = std::thread::scope(|scope| {
let written = AtomicUsize::new(0);
let (done, elapsed, errors, lines) = std::thread::scope(|scope| {
let _stops = StopsTheWriter(&stop);
let writer = scope.spawn(|| {
// Its own connection, which gives up on a lock after one second.
// Its own connection, set up as the app's are (`Store::open`: the log
// and `synchronous = NORMAL`, so that a commit does not wait for the
// disk), with a busy timeout that a slow checkpoint does not reach.
let db = Connection::open(scratch.db()).unwrap();
db.busy_timeout(Duration::from_secs(1)).unwrap();
db.pragma_update(None, "synchronous", "NORMAL").unwrap();
db.busy_timeout(Duration::from_secs(60)).unwrap();
let sql = "INSERT OR REPLACE INTO settings (key, value) VALUES ('probe', ?1)";
let (mut writes, mut errors) = (0, Vec::new());
let mut errors = Vec::new();
while !stop.load(Ordering::Relaxed) {
match db.execute(sql, [writes.to_string()]) {
Ok(_) => writes += 1,
let began = Instant::now();
match db.execute(sql, [written.load(Ordering::Relaxed).to_string()]) {
Ok(_) => {
written.fetch_add(1, Ordering::Relaxed);
}
Err(error) => errors.push(error.to_string()),
}
std::thread::sleep(Duration::from_millis(5));
// It pauses ten times as long as the write took, and 5 ms at least.
// Under disk pressure a commit takes 100 ms and more, and a writer
// that paused 5 ms after each would hold the writer lock nearly all
// the time and keep the sign-out, whose busy timeout is the default
// five seconds, from getting it (`DatabaseBusy`).
let wake = Instant::now() + (began.elapsed() * 10).max(Duration::from_millis(5));
while Instant::now() < wake && !stop.load(Ordering::Relaxed) {
std::thread::sleep(Duration::from_millis(1));
}
}
(writes, errors)
errors
});
// The sign-out starts when the writer is up and has written, not when
// the thread was spawned: a thread of a busy machine can start late.
let deadline = Instant::now() + Duration::from_secs(60);
while written.load(Ordering::Relaxed) == 0 {
assert!(Instant::now() < deadline, "the writer never ran");
std::thread::sleep(Duration::from_millis(1));
}
let started = Instant::now();
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto);
let (done, lines) = support::at_trace(|| {
store.sign_out(&binding().account, DeviceKeyChoice::Forget(key().uid()))
});
let elapsed = started.elapsed();
stop.store(true, Ordering::Relaxed);
let (writes, errors) = writer.join().unwrap();
(done.unwrap(), elapsed, writes, errors)
let errors = writer.join().unwrap();
(done.unwrap(), elapsed, errors, lines)
});
// Four removals: the two copies, the device key the client made, the record.
// Four removals: the two copies, the device key the user forgot, the record.
assert_eq!(done.removed.len(), 4, "{done:?}");
assert!(store.list().unwrap().is_empty());
assert!(writes > 0, "the writer never ran");
assert!(errors.is_empty(), "a concurrent writer failed: {errors:?}");
assert!(elapsed < Duration::from_secs(1), "the sign-out took {elapsed:?}");
// One checkpoint for the four removals: each one that is blocked says so.
let blocked = support::blocked_checkpoints(&lines);
assert_eq!(blocked, 1, "{lines:?} (the sign-out took {elapsed:?})");
// Nothing is lost by the wait: once the reader is gone, the next removal
// truncates the log.
@@ -1758,6 +1819,245 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer(
assert!(RawFiles::read(&scratch).wal.is_empty(), "the log is truncated again");
}
// ------------------------- the keys a sign-out keeps, and the one the user forgets
//
// Open question 10 of the accounts design (Phase 2 task 34): a sign-out keeps
// every device key, and "Forget this device's identity" is the only deletion.
/// Every column of the row of this `(kind, uid)` as SQLite holds it, by name.
fn named_row(db: &Connection, kind: &str, uid: &str) -> Vec<(String, rusqlite::types::Value)> {
db.query_row(
"SELECT * FROM identities WHERE kind = ?1 AND uid = ?2",
params![kind, uid],
|row| {
let names: Vec<String> =
row.as_ref().column_names().iter().map(|n| n.to_string()).collect();
names
.into_iter()
.enumerate()
.map(|(index, name)| Ok((name, row.get(index)?)))
.collect::<rusqlite::Result<Vec<_>>>()
},
)
.unwrap()
}
#[test]
fn the_device_key_survives_a_sign_out_byte_for_byte_in_the_file() {
// Whether it predates the account or the client made it for the account, no
// column of its row changes: the key never carried a binding, and a sign-out
// writes nothing to it.
for bound_existing_key in [true, false] {
let install = signed_in_install_on_file(bound_existing_key);
let uid = key().uid().to_base32();
let db = Connection::open(install.scratch.db()).unwrap();
let before = named_row(&db, KIND_VOELIN, &uid);
assert!(before.len() >= 8, "{before:?}");
let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
assert_eq!(named_row(&db, KIND_VOELIN, &uid), before, "{bound_existing_key}");
let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap();
assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]);
}
}
#[test]
fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row() {
// The store accepts a binding with `synced = false` on the device key (a
// binding with `synced = true` is refused, see the last section). A sign-out
// unbinds it and keeps it: the four binding columns are the only ones that
// change.
const BINDING_COLUMNS: [&str; 4] = ["account", "integration", "integration_rev", "synced"];
for bound_existing_key in [true, false] {
let install = signed_in_install_on_file(bound_existing_key);
let uid = key().uid().to_base32();
let device_only = AccountBinding { synced: false, ..binding() };
install
.store
.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only))
.unwrap();
let db = Connection::open(install.scratch.db()).unwrap();
let before = named_row(&db, KIND_VOELIN, &uid);
let bound = |row: &[(String, rusqlite::types::Value)]| {
row.iter().any(|(name, value)| {
name == "account" && !matches!(value, rusqlite::types::Value::Null)
})
};
assert!(bound(&before), "the setup binds the key");
let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}");
let after = named_row(&db, KIND_VOELIN, &uid);
assert!(!bound(&after), "{bound_existing_key}: unbound");
assert_eq!(before.len(), after.len());
for ((name, was), (_, is)) in before.iter().zip(&after) {
if !BINDING_COLUMNS.contains(&name.as_str()) {
assert_eq!(is, was, "{bound_existing_key}: column {name} is not a binding column");
}
}
let stored = install.store.get(KIND_VOELIN, &uid).unwrap().unwrap();
assert_eq!(stored, IdentityBlob::voelin(&key()).unwrap());
assert!(install.store.bound_to(&binding().account).unwrap().is_empty());
}
}
#[test]
fn a_sign_out_scrubs_the_copies_it_deletes_and_leaves_the_kept_keys_in_the_file() {
// What a sign-out still deletes is a synced copy (a private key, which
// the service holds again) and the record: those are gone from the file and
// its log. The device key and the device-only secret are kept, so their text
// is still there.
let scratch = Scratch::new("scrub-keeps");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let device = IdentityBlob::voelin(&key()).unwrap();
let synced = fresh_teamspeak(binding());
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
let device_text = key_text(&device.json, "pkcs8");
let (synced_text, device_only_text) =
(key_text(&synced.json, "key"), key_text(&device_only.json, "key"));
for blob in [&device, &synced, &device_only] {
store.put(blob).unwrap();
}
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
let neighbour = Store::open(&scratch.db()).unwrap();
let before = RawFiles::read(&scratch);
assert!(before.holds(&device_text) && before.holds(&synced_text));
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
let after = RawFiles::read(&scratch);
assert_eq!(after.where_is(&synced_text), (false, false), "the synced copy");
assert!(after.holds(&device_text), "the device key is kept");
assert!(after.holds(&device_only_text), "the device-only secret is kept");
assert!(after.wal.is_empty(), "the log is truncated");
drop(neighbour);
}
#[test]
fn a_sign_out_that_deletes_nothing_does_not_checkpoint() {
// With no record and no synced copy a sign-out only unbinds. The checkpoint
// belongs to deletions: with a reader that blocks it, a deletion says so, and
// the sign-out does not.
let scratch = Scratch::new("no-deletion");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() });
store.put(&device_only).unwrap();
let reader = Connection::open(scratch.db()).unwrap();
reader.execute_batch("BEGIN").unwrap();
let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 1);
let (done, lines) =
support::at_trace(|| store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap());
assert!(done.removed.is_empty(), "{done:?}");
assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]);
assert_eq!(support::blocked_checkpoints(&lines), 0, "{lines:?}");
// The same reader does block the checkpoint of a deletion, so the count above
// would have shown one.
store.put_voelin_key(&key()).unwrap();
let (removed, lines) =
support::at_trace(|| store.remove(KIND_VOELIN, &key().uid().to_base32()).unwrap());
assert!(removed);
assert_eq!(support::blocked_checkpoints(&lines), 1, "{lines:?}");
reader.execute_batch("COMMIT").unwrap();
}
#[test]
fn a_key_kept_by_a_sign_out_is_exported_and_then_forgotten_without_a_trace() {
// The flow of "Forget this device's identity" after a sign-out: the key is
// still there, unbound; the UI exports it, then deletes it. The export is
// what `voelin_key` and `to_pkcs8` give, and it restores the key.
let scratch = Scratch::new("export-forget");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
let uid = key().uid();
let stored = store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap();
let text = key_text(&stored.json, "pkcs8");
let exported = store.voelin_key(&uid).unwrap().expect("the key is there").to_pkcs8().unwrap();
assert!(RawFiles::read(&scratch).holds(&text));
assert!(store.remove(KIND_VOELIN, &uid.to_base32()).unwrap());
assert!(store.voelin_key(&uid).unwrap().is_none());
let after = RawFiles::read(&scratch);
assert_eq!(after.where_is(&text), (false, false), "nothing of the key is left");
assert!(after.wal.is_empty(), "the log is truncated");
// The export brings the same key back.
let restored = IdentityKey::from_pkcs8(&exported).unwrap();
assert_eq!(restored.uid(), uid);
assert_eq!(restored.sign(b"the exported key"), key().sign(b"the exported key"));
store.put_voelin_key(&restored).unwrap();
assert_eq!(store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap(), stored);
}
// ------------------------------------------ releasing the device key from its account
//
// `AccountClient::release` asks the service to release the key and then runs the
// local sign-out with `Auto` (protocol 13.6, "Releasing this device's key"), so
// the store's part is the sign-out of the tests above, and the key has to be
// usable for another account afterwards.
#[test]
fn the_local_half_of_a_release_keeps_the_key_and_it_serves_another_account() {
let Install { store, .. } = signed_in_install(false);
let uid = key().uid().to_base32();
let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap();
let signature = key().sign(b"the same key, before and after the release");
// The service released the key; the device finishes with a local sign-out.
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
assert!(!done.removed.contains(&device_key_info()), "{done:?}");
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte");
assert_eq!(store.account_record().unwrap(), None);
// The key is registered with no account and signs up for another one: its
// record names the same key, and a copy of the new account's material is
// bound to it.
let other_id = AccountId::from_bytes([42; 16]);
let other = AccountRecord { account_id: other_id, login: "bob".into(), ..record() };
store.put_account_record(&other).unwrap();
assert_eq!(store.account_record().unwrap(), Some(other.clone()));
let other_binding = AccountBinding { account: account_uid(&issuer(), &other_id), ..binding() };
let other_copy = fresh_teamspeak(other_binding);
store.put(&other_copy).unwrap();
// Signing out of the new account keeps the key again, and the copy goes.
let done = store.sign_out(&other_binding.account, DeviceKeyChoice::Auto).unwrap();
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
assert!(done.removed.contains(&info_of(&other_copy)), "{done:?}");
let kept = store.voelin_key(&key().uid()).unwrap().expect("the key stays");
assert_eq!(kept.sign(b"the same key, before and after the release"), signature);
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before, "byte for byte");
}
#[test]
fn a_release_whose_local_half_was_cut_short_is_finished_by_a_sign_out() {
// The service released the device and the call was dropped before the local
// sign-out took the slot: the record and the copies are still here, and the
// key is still the record's device key. A sign-out with `Auto` finishes it
// and keeps the key; running it again finds nothing to do.
let Install { store, synced, device_only, .. } = signed_in_install(true);
let uid = key().uid().to_base32();
let before = store.get(KIND_VOELIN, &uid).unwrap().unwrap();
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert!(done.removed.contains(&info_of(&synced)), "{done:?}");
assert!(done.unbound.contains(&info_of(&device_only.clone().with_binding(None))), "{done:?}");
assert_eq!(store.account_record().unwrap(), None);
assert_eq!(store.get(KIND_VOELIN, &uid).unwrap().unwrap(), before);
assert_eq!(
store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(),
SignOut::default()
);
}
// -------------------------------------- the device key is never a synced copy
//
// `KeyStore::sign_out` deletes everything bound with `synced = true` in its
@@ -1798,15 +2098,15 @@ fn a_synced_binding_on_the_device_key_is_refused_with_a_precise_error() {
assert_eq!(store.list().unwrap().iter().filter(|i| i.binding.is_some()).count(), 0);
// A binding that is not synced is a device-only secret: accepted, and a
// sign-out unbinds it and keeps it (or deletes it, as the record says).
// sign-out unbinds it and keeps it.
let device_only = AccountBinding { synced: false, ..binding() };
store.put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)).unwrap();
store.put(&before).unwrap();
// So the sign-out still does what the record says with the key.
// So the sign-out keeps the key, whether it predates the account or not.
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap();
assert_eq!(done.unbound.contains(&device_key_info()), bound_existing_key, "{done:?}");
assert_eq!(store.voelin_key(&key().uid()).unwrap().is_some(), bound_existing_key);
assert!(done.unbound.contains(&device_key_info()), "{done:?}");
assert!(store.voelin_key(&key().uid()).unwrap().is_some());
}
}
+87
View File
@@ -0,0 +1,87 @@
//! Helpers the integration tests of this crate share.
// Each integration test crate of this directory uses some of these helpers.
#![allow(dead_code)]
use std::fmt::{self, Write as _};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use tracing::field::{Field, Visit};
use tracing::level_filters::LevelFilter;
use tracing::span::{Attributes, Id, Record};
use tracing::{Event, Metadata, Subscriber};
/// A subscriber that keeps every event and span it sees as one line of text
/// each: level, target and every field with its `Debug` text, as a log line
/// would show them.
struct Capture {
lines: Arc<Mutex<Vec<String>>>,
spans: AtomicU64,
}
impl Capture {
fn push(&self, line: String) {
self.lines.lock().unwrap_or_else(PoisonError::into_inner).push(line);
}
}
/// The fields of an event or a span as ` name=value` text.
struct Fields<'a>(&'a mut String);
impl Visit for Fields<'_> {
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
let _ = write!(self.0, " {}={value:?}", field.name());
}
}
impl Subscriber for Capture {
fn enabled(&self, _: &Metadata<'_>) -> bool {
true
}
fn max_level_hint(&self) -> Option<LevelFilter> {
Some(LevelFilter::TRACE)
}
fn new_span(&self, attributes: &Attributes<'_>) -> Id {
let mut line = format!("span {}", attributes.metadata().name());
attributes.record(&mut Fields(&mut line));
self.push(line);
Id::from_u64(self.spans.fetch_add(1, Ordering::Relaxed) + 1)
}
fn record(&self, _: &Id, values: &Record<'_>) {
let mut line = String::from("span record");
values.record(&mut Fields(&mut line));
self.push(line);
}
fn record_follows_from(&self, _: &Id, _: &Id) {}
fn event(&self, event: &Event<'_>) {
let metadata = event.metadata();
let mut line = format!("{} {}:", metadata.level(), metadata.target());
event.record(&mut Fields(&mut line));
self.push(line);
}
fn enter(&self, _: &Id) {}
fn exit(&self, _: &Id) {}
}
/// Run `f` on this thread with a subscriber that takes in everything logged at
/// TRACE and above, and return what `f` returned with the lines logged.
pub fn at_trace<R>(f: impl FnOnce() -> R) -> (R, Vec<String>) {
let lines = Arc::new(Mutex::new(Vec::new()));
let subscriber = Capture { lines: Arc::clone(&lines), spans: AtomicU64::new(0) };
let out = tracing::subscriber::with_default(subscriber, f);
let lines = std::mem::take(&mut *lines.lock().unwrap_or_else(PoisonError::into_inner));
(out, lines)
}
/// How many of the lines say that a checkpoint was blocked.
pub fn blocked_checkpoints(lines: &[String]) -> usize {
lines.iter().filter(|line| line.contains("another connection blocked the checkpoint")).count()
}
+2 -1
View File
@@ -1075,7 +1075,8 @@ impl Task {
}
Event::IceConnectionStateChange(IceConnectionState::Disconnected) => return false,
Event::MediaAdded(m) => {
if !self.mids.iter().any(|(mid, _)| *mid == m.mid) {
let known = self.mids.iter().any(|(mid, _)| *mid == m.mid);
if !known {
self.mids.push((m.mid, m.kind));
}
}
Loaded 100 of 224 files, more files were not shown because too many files have changed in this diff. Show more