Files
VoelinClient/docs/session-seam.md
T
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

82 KiB
Raw Blame History

The session seam: the engine on voelin_proto::link::Session

Status: design (2026-10-20); slice 1 is implemented (section 13 says how it differs from this text, section 14 what the review changed); section 10 has the slices.

Design for the first half of plan step 7 (Phase 4): the engine consumes voelin_proto::link::Session, ServerLink becomes an adapter over it, and the TeamSpeak link (TsLink) becomes a Session implementation that still lives in this repository, in process. The second half (the TeamSpeak Session implementation moves to VoelinGateWay as voelin-gateway-ts, and voelin-stream's dependency on voelin-media is split) is out of scope here; section 11 lists what it has to do.

Read for this design: crates/voelin-core/src/link.rs, ts_link.rs, voice.rs, book.rs, stream.rs, files.rs, session.rs (its use of the link), tests/link_fake.rs, voelin-audio/src/packet.rs; and in VoelinProtocol (main c8e0e5a) crates/voelin-proto/src/link.rs, media.rs with media/, test_util/ (FakeHost, FakeSession, FakeConnector, FakeAccountAgent, the conformance suite), proto/voelin/v1/*.proto, crates/voelin-model/src/replica/ and docs/protocol.md sections 1.2, 1.3, 2.4, 2.5, 4.7, 5, 6, 9.1, 11 and 13.8.

1. Terms and the decisions in one place

Term Meaning here
engine voelin-core without the TeamSpeak implementation: lib.rs, session.rs, history, contacts, cache, settings, the audio thread, the adapter below.
SessionLink New, engine side. A ServerLink whose connections are Arc<dyn Session>s from the registry: it turns LinkCmds into Session calls and pushes, signals and media into LinkEvents. session.rs keeps talking LinkCmd/LinkEvent to it.
Backends New, engine side. The registry of connectors by address scheme: voelin_proto::link::Connectors plus the in-process connectors that also hand the engine local ports (below).
LinkSession New, TeamSpeak side. A Session over any ServerLink, generic in the link. LinkSession<TsLink> is the in-process TeamSpeak Session; LinkSession<FakeLink> is what the link tests run through.
TsConnector New, TeamSpeak side. The Connector for ts3server and teamspeak (and addresses without a scheme) that makes LinkSession<TsLink>s.
StreamPort New, local extension. The in-process channel that carries LinkCmd::Stream and the stream events past the Session trait while TeamSpeak 6 streams are not yet v1 entities (section 6.4).
old model The client's TeamSpeak-shaped types (Presence, ChannelInfo, ClientInfo, ChatMessage, ServerDetails) that session.rs and the UI use.

Decisions:

  1. Two adapters, one vocabulary in the middle. session.rs is not rewritten: it keeps LinkCmd/LinkEvent. SessionLink translates them to and from v1; LinkSession translates v1 to and from the inner link's LinkCmd/LinkEvent. With a fake link inside, the pair round-trips, so the existing FakeLink tests check both translations (slice 1).
  2. The engine keeps a replica. SessionLink feeds every push into voelin_model::replica::Replica and projects it into the old model with replica::convert plus the fix-ups of section 5.3. This needs the protocol's voelin-model (a superset of the client's, byte for byte the same in presence.rs, server.rs, chat.rs, percent.rs), so slice 1 switches the client's voelin-model to the protocol crate (the plan's section 4 already moves it there). Two crates named voelin-model in one graph would make scripts/own-crates.sh's -p voelin-model ambiguous, so there is no half-way.
  3. Streams stay on a local port in this half. TeamSpeak 6 streams are peer to peer; v1 carries only their signalling (Stream, Viewer, RespondViewer, KickViewer, Signal{stream}, protocol 6.11 and 11.1). Moving the str0m peer out of the TeamSpeak stream task and mapping its signalling is the second half's first item; here LinkCmd::Stream and the stream events pass through StreamPort, unchanged.
  4. File transfers go through v1 now. read_file/write_file carry them; the engine does the copying, progress and cancel itself, and the TeamSpeak side hands out the raw transfer connection (two new inner commands, section 8).
  5. TeamSpeak-only connect options ride the ts3server:// link that voelin_model::link::ServerLink::to_url already writes (channel/cid, channelpassword), until v1 has a field for them (follow-up P1); the client version TsConnector impersonates rides it too, as a parameter of our own (client_version).
  6. No TeamSpeak type crosses the seam: what crosses is voelin_proto types, the old model (TeamSpeak-shaped, but the client's own types), voelin-audio packets and the core-owned stream types. Section 10 says which public items still name voelin-stream peer types, and why.

2. Shape after this half

UI ── Engine (Command / Event) ── session.rs (merge, dedup, history, contacts)
                                     │ LinkCmd ↓   ↑ LinkEvent
                                  SessionLink (engine side: replica, projection,
                                     │          media framing, transfers, talk tracker)
                                     │ Arc<dyn Session> + pushes + MediaSink
                                     │ (+ StreamPort for in-process connectors)
                       Backends ─────┼──────────────────────────┐
                 (scheme registry)   ▼                          ▼
              TsConnector → LinkSession<TsLink>       any Connector: FakeConnector
              (ts3server, teamspeak, no scheme)        (tests), QuicConnector (later)
                                     │ LinkCmd ↓ ↑ LinkEvent (inner, TS side)
                                  TsLink: voice.rs, book.rs, stream.rs, versions.rs,
                                          identity.rs on tsclientlib, voelin-stream

The gateway (tsgw) and ServerQuery sources of a session are not behind the seam in this half: they are the other two sources of session.rs (gateway.rs, query.rs) and become a second Session to a gateway daemon later (protocol 11.2, follow-up H5). Only their public command types change in slice 3 (section 10).

3. The mapping

3.1 LinkCmd → Session

Every variant of voelin_core::link::LinkCmd. "SessionLink" is what the engine does; "LinkSession" is how the TeamSpeak side answers. S is the server id from the connect sequence (section 4.2), P our participant id, slot our media slot. Text in errors is reproduced exactly as TsLink writes it today (section 4.6).

LinkCmd Session call (SessionLink) Answer and what the engine reports LinkSession (TeamSpeak side)
SendChat(target, text) request(Put{writes:[Message{channel_id, text, format, nonce}]}). Channel(cid): that channel. Server: the channel of kind SERVER_CHAT in SERVER(S). Private(uid): the DM channel in HOME whose other recipient's User has that uid; without one, first request(Put{Channel{server_id:0, kind:DM, recipients:[user]}}). format: BBCODE when the session offers chat.bbcode, else MARKDOWN. Entities ignored (the Change that follows is the echo, section 3.2). Rejected → LinkEvent::Error("message: {Error.message}"). No User for uid → Error("private message: the client is not on the server (send an offline message instead)"), without a request. Inner SendChat. A VOICE channel other than our own is refused NOT_IN_CHANNEL. Answered at once with the message as written (local id and rev): TsLink reports success of a text message nowhere, failures come later as a notice (section 3.2). The answer adds no Change: the inner link's echo is the Change, with an id of its own, because the inner link does not tie the echo to the send (H1 does). A Put Channel{DM} answers the synthetic DM channel (section 5.2) and puts it in HOME.
Move(channel, password) request(JoinVoice{server_id:S, channel_id, password}) (None → empty). Own VoiceState → nothing (the move shows in LIVE). Rejected → Event::JoinFailed{channel, reason}: PASSWORD → JoinFailure::Password, FULL → Full, any other → Other(Error.message). Already in that channel: answer the own VoiceState, send nothing (today ChannelAlreadyIn is silent too). Else inner Move; answered when our channel becomes channel_id (own VoiceState), refused when the inner link reports Event::JoinFailed for it (Password → PASSWORD, Full → FULL, Other(text) → FORBIDDEN with text), SessionError::Timeout after 10 s. The first JoinVoice of a connection confirms the seat (section 4.2).
SetInputMuted(b) notify(Put{Write{VoiceState{S, P, self_mute:b}, paths:[self_mute]}}) (protocol 4.7: own voice flags are fire and forget). Err only for a closed session: ignored. Inner SetInputMuted(b).
SetOutputMuted(b) notify(Put{Write{VoiceState{S, P, self_deaf:b}, paths:[self_deaf]}}). As above. Inner SetOutputMuted(b).
Audio(EncodedVoice) send_media(MediaClass::Voice, MediaPacket{flow: FlowId::new(slot, voice_sub::CHANNEL), rtp}), RTP as in section 6.1. Dropped: counted (stats). NotOwned (no slot yet), TooLarge (over stats().max_rtp): dropped, logged once per connection. Closed: ignored. Inner Audio(EncodedVoice{codec, payload}) for our own slot only (section 6.2).
Stream(StreamCmd) None in this half: StreamPort::send(cmd) (section 6.4; the v1 mapping of every StreamCmd is table 6.4). Without a port the engine reports no streams capability, so session.rs never sends it. Bus events and OwnStream/StreamAudio/StreamAudioEnded come back through the port. Inner Stream(cmd), in issue order with everything else (one queue).
Poke{client, message} request(Signal{to:SignalTarget{server_id:S, participant_id:client}, body:Poke{message}}). Ack → nothing. Rejected → Error("poke: {Error.message}"). Inner Poke; answered Ack at once (failures come as a notice).
ListFiles{request, dir} request(List{kind:FILE, parent:dir.channel, path:dir.path, password}) (refused locally without files). Event::FileList{request, channel, path: files::normalize_dir(path), result}: Ok with each FileEntry as files::FileEntry{name, size, modified_s: modified_ms/1000, is_dir}, or Err(text). Inner ListFiles with a request id of its own; its Event::FileList becomes the Entities answer (modified_ms = modified_s * 1000), or Rejected with the text.
Download{transfer, file, sink, report} report(Requested), then read_file(FileRead{target: Path(FilePath{channel_id, path, password}), offset: sink.offset(), length:0}); the engine runs files::download (made generic over AsyncRead) on Download.body with FileEntry.size from head. A picture (transfer: None) keeps today's limit (cache::MAX_PICTURE_BYTES) and deadline (image_download_time), now applied here. TransferStates through report, as today. Err → report(Failed(text)). The task is kept under transfer for CancelTransfer. Inner OpenRead (new, section 8): the TeamSpeak transfer connection itself becomes body, head is FileEntry{size}.
Upload{transfer, file, from, overwrite, resume, report} Size and kind of from checked here (today's texts: "{path} is not a file", "{path}: {error}"). With resume, the offset is the size of the target in List{FILE} of its directory (0 when absent). write_file(FileWrite{target: Path(...), size, offset, overwrite}); the engine runs files::upload (generic over AsyncWrite) into Upload.body, then awaits Upload.done. TransferStates as today; Done after done resolved. Inner OpenWrite (new): the transfer connection becomes body; the server's seek position must equal offset, else CONFLICT "the server has N bytes" (follow-up P4). done resolves when the inner job reports the end.
CancelTransfer(id) No call: the engine aborts its copy task (dropping the body cancels on both v1 and TeamSpeak), removes the .part file, reports Cancelled; an unknown id is logged, as today. — The dropped connection ends the TeamSpeak transfer.
DeleteFiles{request, channel, password, paths} request(Delete{keys:[FileEntry{channel_id, path: dir, name, password}...]}), one key per path (/dir/name split at the last /). request: Some → Event::RequestDone{request, result}; None → nothing (best effort). Keys grouped by channel → inner DeleteFiles{request: Some(own id)} each; RequestDone → Ack or Rejected.
RenameFile{request, from, to} request(Put{writes:[Write{FileEntry{channel_id: to.channel, path, name, password: to.password, from_channel_id: from.channel, from_path: from.path, from_password}}]}) (a create of an unused key: no paths). RequestDone{request, result}. Inner RenameFile.
CreateDirectory{request, dir} request(Put{writes:[Write{FileEntry{channel_id, path, name, is_dir: true, password}}]}). RequestDone{request, result}. Inner CreateDirectory.
SetAvatarHash{request, hash} request(Put{writes:[Write{User{id: own user, avatar: Image{hash}}, paths:[avatar.hash]}]}) (the leaf path, so the myTeamSpeak url in the same Image stays). Some(request) → RequestDone; None → Rejected becomes Error("avatar: …"). Inner SetAvatarHash. (replica::convert reads the TeamSpeak avatar from User.avatar.hash; follow-up P7 on Member.avatar.)
OfflineList{request} request(List{kind:MAIL}) (refused locally without mailbox). Event::OfflineMessages{request, result} from the Mails (OfflineMessageInfo fields from id, from_uid, from_name, subject, ts_ms, read). Inner OfflineList; its event becomes Entities[Mail…].
OfflineGet{request, id} request(List{kind:MAIL, ids:[id]}) (v1: List{MAIL, ids} returns the text). Event::OfflineMessage{request, result}. Inner OfflineGet.
OfflineAdd{request, to_uid, subject, text} request(Put{writes:[Write{Mail{id:0, to_uid, subject, text}}]}). RequestDone. Inner OfflineAdd; answers the mail as written (id 0: messageadd returns none).
OfflineDelete{request, id} request(Delete{keys:[Mail{id}]}). RequestDone. Inner OfflineDelete.
OfflineFlag{request, id, read} request(Put{writes:[Write{Mail{id, read}, paths:[read]}]}). RequestDone. Inner OfflineFlag.
Disconnect close(CloseCode::Normal, ""), then closed(). A closed command channel does the same. LinkEvent::Disconnected(None) (section 4.5). Inner Disconnect; closed() resolves Local(Normal) when the inner link reports its end.

Requests with a RequestId that cannot be sent (no session yet, closed) answer as today: session.rs already reports "not connected with voice" before a link exists; SessionLink reports SessionError texts (4.6).

LinkSession::notify follows the Session contract (it errors for a closed session or a misplaced op, as FakeSession does): Hello, List, FileRead and FileWrite are Protocol errors, because they have a stream and an answer of their own (placement); our own mute flags go to the link; any other op of the control stream is run as the request it is, and its answer, or its refusal, is told to nobody.

3.2 Session → LinkEvent

Every variant of voelin_core::link::LinkEvent.

LinkEvent Source on the Session side Rule
Connected{name, backend, capabilities, own_client, server_uid, own_uid} Welcome, the SERVER(S) sync, the answer to the first JoinVoice, the own User. Sent once, after the connect sequence (4.2). name = Server.name; backend from Welcome.host.backend (table 4.7); capabilities from features() (table 4.7); own_client = P as u16; server_uid = server_key(Server.uid) (5.3, F3); own_uid = uid_text of the own User (the User of our VoiceState.user_id, else Welcome.user_id), None when the replica has none yet.
Presence(Box<Presence>) Change/SyncEnd of SERVER(S) and LIVE(S); talk tracker. After the pushes that are there now are applied (drain, then one snapshot), if SERVER or LIVE changed: replica.presence_model(S) with the fix-ups F1-F10. One TeamSpeak book update is one inner Presence, one or two Changes, and still one snapshot.
OwnChannel(cid) Our VoiceState.channel_id in LIVE. After every Presence, when known and not 0 (as TsLink does after every snapshot). Our VoiceState is the one of the seat, and behind a TeamSpeak server it follows the seat to the participant that is us after the link's own reconnect (4.4); the OwnChannel of the inner link only tells LinkSession that a move has arrived.
Chat(ChatMessage) Change.put of a Message, and messages of a SyncBegin..SyncEnd, in a subscribed CHAT scope (4.3). Once per (channel_id, id) per connection, and only once the replica can show it: a full sync stages its messages until its SyncEnd, so the messages of a CHAT scope are reported at its SyncEnd as well (4.3). replica.chat_message(channel, id) gives target, author name, author uid, author participant, ts_ms, via_relay (MESSAGE_FLAG_RELAYED). Answers to our own Put are not applied to the replica: our own message is reported when its Change arrives, which is today's echo, and session.rs merges it with the row it stored (test a_sent_message_and_its_echo_are_one_message).
Poke{from, from_uid, from_name, message} Push Signal{from_user, from_participant, body: Poke{message}}. from = from_participant as u16; from_uid = uid_text of User(from_user); from_name = the participant's VoiceState.nick, else the User.name. A sender outside our view is delivered as a bare User first (5.2).
Audio(VoicePacket) MediaSink packets on a voice slot. Section 6.1.
Talking{client, talking} MediaSink packets on a voice slot (protocol 6.4: talking in the own channel comes from media), and Signal{speaking} (below). The first packet of a slot → true; 400 ms without one → false (250 ms tick): the rule of voice.rs today. TsLink also hears talkers whose packets it does not forward as Opus (Speex, CELT): LinkSession passes the inner link's Talking on as Signal{speaking}, and SessionLink holds such a talker as talking until the host says on: false (no silence ends it). Also fills ClientInfo.talking (F8).
OwnStream(OwnStreamEvent) StreamPort events. Passed through.
StreamAudio{stream, time, data} StreamPort events. Passed through.
StreamAudioEnded(stream) StreamPort events. Passed through.
Error(text) (a) Rejected answers to commands that have no RequestId (SendChat, Poke, SetAvatarHash{request: None}); (b) push Signal{notice{level: ERROR or WARNING}}; (c) ScopeClosed of SERVER(S) or LIVE(S). (a) "{what}: {Error.message}", what = message, poke, avatar (today's labels); (b) Notice.text; (c) ScopeClosed.message, and the presence is emptied.
Disconnected(reason) closed(); a failed connect; a connect sequence that does not finish. Section 4.5. Sent once; the StreamPort's closing events may follow, as the contract of link.rs already allows.

What the Session side produces and no LinkEvent carries, with the decision for each:

Session output Decision in this half
Push::SyncBegin/SyncEnd/Change of HOME Applied to the replica: DM channels (CHAT subscriptions, 4.3), the own User, bare Users of senders. No event of their own.
Push::Heads Ignored: no unread source in the engine uses it yet (TeamSpeak sends none).
Push::HostUpdate Updates the feature set SessionLink checks requests against. Capabilities are not announced again: LinkEvent has no update, and TeamSpeak never sends one. Follow-up (client): Event::ServerInfo again on a HostUpdate.
Push::ScopeClosed CHAT: unsubscribed, nothing reported. SERVER or LIVE: Error and an empty presence (row Error above). HOME: logged.
Signal{typing} Ignored (the engine has no typing indicator; TeamSpeak types only in DMs).
Signal{stream}, Signal{layer_target} Not sent by LinkSession (streams use the port). Ignored with a log. Second half: the engine's stream task (H2).
Signal{encoder_hint} Ignored. Follow-up (client): Opus bitrate and packet_loss_perc from it (protocol 6.7).
Signal{reminder} Ignored (no events feature in the engine).
Signal{notice{level: INFO}} Logged at info.
Signal{speaking} A hint next to the media: the host says a participant talks or stopped (LinkSession sends it for the inner link's Talking, which is all there is for a talker without Opus). Not asked for with SUBSCRIBE_OPTION_SPEAKING; talking in other channels stays a follow-up (P13).
Media on stream slots (sub 0-4), FlowId::FEEDBACK, FlowId::PROBE Dropped (no SFU streams in this half).
stats() (LinkStats) Section 4.7.
Connected.host_uid Not pinned for TeamSpeak ([0; 32], no host key). Kept for a later pin store for voelin:// hosts.
Welcome.resume_token, Welcome.ice, Welcome.observed_addr, Welcome.time_ms Kept by SessionLink, unused in this half (4.4).
Welcome.limits max_chat_subscriptions bounds the CHAT scopes (4.3). max_message_chars is not enforced (the UI's own limit stays).

4. How the engine owns a Session

4.1 The registry

voelin_core::link::Backends holds the connectors by scheme:

  • connectors: voelin_proto::link::Connectors for plain connectors (Backends::register(Arc<dyn Connector>): FakeConnector in tests, the QUIC connector later);
  • in-process connectors that also give local ports: a crate-private trait LocalConnector: Connector with connect_local(params, LocalCtx) -> BoxFuture<Result<LocalConnected, SessionError>>, where LocalCtx is what an in-process backend needs besides ConnectParams (session id, the event bus, the frames bus, the settings, the stream peer configuration, whether audio is open) and LocalConnected is Connected plus Option<StreamPort>.

Lookup: the scheme of ConnectParams.address (lowercase, before ://); an address without a scheme is a TeamSpeak bookmark and gets ts3server. A local connector for the scheme wins over a plain one; none → Disconnected with "no connector for {address}" (the text of Connectors::connect, but with the address cut at ? and #: the text is shown and logged, and a TeamSpeak link carries a channel password and a pin).

Engine::start and start_with use Backends::default(), which registers TsConnector (schemes ts3server, teamspeak) with the engine's myTeamSpeak watches (4.8). New: Engine::start_with_backends(settings, history, backends). Engine::start_with_link(settings, history, link) stays in slices 1 and 2: it registers a local LinkConnector that answers every scheme with a LinkSession over the given link, so the link tests go through the whole adapter.

4.2 Connect sequence

SessionLink is a ServerLink: session.rs calls spawn exactly as today and shows Connecting until Connected.

  1. Build ConnectParams (section 7 for the credential). In slice 1 the options still carry TeamSpeak types, so one function of the TeamSpeak module, ts_session::connect_params(&ConnectOptions), builds them; it also writes the resolved client version into the link parameter client_version in a text form of its own. Slice 3 moves the building into SessionLink over the neutral VoiceOptions, and client_version carries the user's spec instead. The fields: address = the ts3server:// link of the bookmark address with channel/cid and channelpassword (ServerLink::to_url of the model's link.rs; a name clash with the trait, nothing more), or the address as given when it has a scheme; hello = Hello{version:1, client: ClientInfo{name:"Voelin", version, platform, kind}, nickname, password: server password, invite_code: privilege key, ..}; host_pin: None; trust: refuses (no TOFU dialog yet; TeamSpeak has no host key); media: SessionLink's sink; push_capacity: 1024; timeout: 35 s (the TeamSpeak connect gives up at 30 s with its own text, which should win); account: None, issuer_trust: Unknown, linked: []. The link can hold a channel password: neither side logs it (the connector logs the host and port), and session.rs keeps keying history and aliases by the bookmark address, not by the link.
  2. Backends::connect. Err(e) → Disconnected(Some(text(e))), end.
  3. request(List{kind: SERVER}); the server S is the only one listed (or the lowest id; follow-up P3 for hosts with several). FakeHost files no Server stub in HOME (follow-up P9), so HOME is not used to find it.
  4. Subscribe HOME, SERVER(S) and LIVE(S), each after replica.subscribe.
  5. Apply pushes until the three SyncEnds. 30 s without them → close, Disconnected(Some("timed out while connecting")). If the push channel ends meanwhile the session has ended: closed() says why, and that is the reason of Disconnected (a kick during the syncs is shown as one).
  6. request(JoinVoice{server_id:S, channel_id, password}): channel_id from the bookmark's channel (/<id> directly, a path resolved in the synced tree with split_channel_path), else Server.default_channel_id. The answer is our VoiceState: P, slot. TeamSpeak seats a client at connect, so LinkSession answers the first JoinVoice of a connection with the seat it has (participant = our client id, channel as far as it knows it, 0 before the first snapshot) and moves nothing; the seat was chosen by the link's channel parameter. A refused first JoinVoice → close, Disconnected(Some(Error.message)).
  7. Report Connected, then Presence, then OwnChannel (the order session.rs and its tests expect).
  8. Subscribe CHAT for the server chat, our channel and each DM (4.3).
  9. Loop, select! biased in this order: the command channel, pushes, media, closed(), the 250 ms tick (talk tracker, stats). Pushes before media, so a talker's VoiceState is known before their first packet (both come from one in-process task on the TeamSpeak side).

LinkSession answers List{SERVER}, Subscribe and Unsubscribe from its own state, without an inner command; an op it does not implement is UNSUPPORTED with the op's feature in Error.feature.

4.3 Which CHAT scopes

TeamSpeak delivers the chat of our own channel, the server chat and private messages; everything else needs a gateway. SessionLink subscribes exactly that: CHAT(server chat channel), CHAT(our channel) (re-subscribed when we move, the old one unsubscribed), and CHAT(dm) for each DM channel HOME holds.

The number of CHAT scopes is Welcome.limits.max_chat_subscriptions (0 or no Limits: the v1.0 default, 16). LinkSession says 65,536 and enforces it: it is no limit a connection reaches, because a private message from somebody new makes a conversation, and a connection on a busy server meets more than 16 people. Against a host with a small limit the server chat and our channel come first, then the private conversations, the newest (highest id) first.

A message that arrives before its scope is subscribed is not lost: LinkSession keeps the messages of the connection per channel (the 50 newest, the default CHAT window of protocol 5.4) and sends them in the full sync; SessionLink reports each (channel, id) once. A full sync is staged by the replica until its SyncEnd, so a message of its Changes cannot be read when the Change is applied (and SyncBegin, Change and SyncEnd may come in different batches): SessionLink marks a message as reported only once it has shown it, and at the SyncEnd of a CHAT scope it shows the messages of that channel it has not shown yet (test the_messages_of_a_chat_sync_are_reported_when_the_sync_ends). A first private message from someone new therefore arrives as: HOME Change (the DM channel), Subscribe CHAT(dm), its sync. A cursor kept per CHAT scope makes a re-subscription after moving back a delta where the session offers sync.delta (LinkSession does, within one connection).

4.4 Reconnect and resume

  • Engine-initiated (Command::ConnectVoice again): unchanged. session.rs gives the old link StreamCmd::Shutdown, then Disconnect; both reach the old session through one ordered queue (4.5), and the generation filter drops what the old one still says.
  • Transport: TeamSpeak's own reconnect inside tsclientlib (DisconnectedTemporarily) stays invisible at the seam, as it is today (the snapshots go on). The connection comes back as another client: a new client id, the same unique id and database id. LinkEvent::Connected is not repeated (as today), but the engine does not stay the client of the connect: we are the client of our unique id. LinkSession takes the client it was for as long as that client is in the snapshots, and when it is gone the client of our unique id (the newest, when a ghost of the old connection lingers: while the ghost is there we stay on it, as a second client of one identity may be a second connection of ours); the own client keeps the database id when two clients share it, so the user we are is the same through the reconnect; Session.send_media follows the slot. SessionLink (behind a TeamSpeak host only: a participant is ours for the life of any other session) keeps its seat while the participant is ours, and moves it to the participant that carries our user id when the seat is gone or no longer carries it; a seat whose user id changed by itself (the snapshot that tells our database id came after the seat) is followed. OwnChannel, the voice flags, the uplink slot and the chat scope of our channel follow the seat (tests the_engine_follows_a_reconnect_that_makes_us_another_client, we_stay_the_client_we_were_while_it_is_there). The native TeamSpeak session of the second half starts a new epoch instead (H1).
  • Resume: LinkSession does not offer resume. SessionLink keeps the last Welcome.resume_token and the CHAT cursors per session and address, and sends neither in this half: no voelin:// connector is registered. Reconnecting with backoff (protocol 2.5) is the SDK's (H8).

4.5 Close

How it ended closed() LinkEvent::Disconnected
LinkCmd::Disconnect, or the command channel closed Local(Normal) None
The inner link ended unasked without a reason Remote{code: Normal, reason: ""} None
The inner link ended with a reason (kicked, server gone, timeout) Network(reason) Some(reason)
A v1 host closed with a code Remote{code, reason} Some(reason), or the code's name when reason is empty; None for Normal with no reason
Idle timeout TimedOut Some("timed out")

LinkSession keeps one queue for everything that reaches the inner link: Session calls, StreamPort sends and close. The order a caller issues them in is the order the inner link sees (the Session contract for mutations, and what a_reconnect_shuts_the_streams_down_before_the_old_connection checks: Stream(Shutdown) before Disconnect).

4.6 Errors and their texts

text(SessionError): Rejected(e) → e.message; Closed(reason) → the reason as in 4.5; Timeout → "timed out while connecting" during connect, "timed out" otherwise; Unsupported(f) → "not offered by this server: {f}"; HostIdentity(t), Protocol(t) → t; Io(e) → e.to_string(). LinkSession puts TsLink's own texts in Error.message and CloseReason::Network, so what the user reads does not change.

4.7 Where Features, BackendInfo and LinkStats surface

Welcome.host.backend → BackendInfo:

v1 BackendInfo{product, flavor} engine BackendInfo.product
teamspeak, ts3 TeamSpeak 3
teamspeak, ts6 TeamSpeak 6
teamspeak, empty (not recognised) empty (version = what the server said)
anything else product as given

LinkSession writes the inverse from the inner Connected.backend (TeamSpeak 3 → teamspeak/ts3, ...), so every value round-trips.

features() (narrowed by Server.features) → Capabilities:

Capabilities from
streams streams, and the connection has a StreamPort (this half)
file_transfer files
offline_messages mailbox
raw_query, ssh_query, http_query no feature: they describe ServerQuery access to a TeamSpeak server, not the session. Derived from the flavor as ServerFlavor::capabilities does (ts3: raw and SSH; ts6: SSH and HTTP). They go with the query observer (H5); follow-up P10.

LinkSession's features are what it implements: voice, chat, chat.bbcode, dm, sync.delta, roles, roles.channel; with file transfer files, files.upload; with offline messages mailbox; with streams streams, streams.p2p, streams.audio, streams.approval. Not voice.whisper, chat.typing or the moderation set: the inner link cannot do them (the native session of H1 offers the whole TeamSpeak column of protocol 9.1). SessionLink refuses locally (Features::require) what needs a missing feature: List{FILE}, file reads and writes (files, files.upload), Mail (mailbox).

LinkStats: no UI surface in this half (the engine has no event for connection quality). SessionLink reads stats() on the tick: max_rtp bounds outgoing voice packets; rtt, loss, media_dropped and degraded are logged at debug every 10 s and when degraded changes. LinkSession reports max_rtp: MAX_RTP and zeros. Follow-ups: an engine event for connection quality, and the encoder's FEC and loss from LinkStats and encoder_hint (protocol 6.7).

4.8 What LinkCtx becomes

LinkCtx field Where it goes
session SessionLink (it reports with it); LocalCtx.session for the stream task.
events SessionLink reports answers itself; LocalCtx.events for the stream task's bus events. Inside LinkSession, the inner link gets a bus of its own: FileList, JoinFailed, OfflineMessages, OfflineMessage and RequestDone from it answer pending requests, every other event (the stream task's) is forwarded to the engine's bus unchanged. Capacity 4096, and every pending request has a timeout, so a lagging receiver cannot hang one forever.
frames LocalCtx.frames, passed to the inner link as is.
settings SessionLink (progress cadence files.progress_ms); LocalCtx.settings for the stream task.
myts_identity, myts_data TsConnector (it gets the engine's watches in slices 1 and 2, has its own setters in slice 3); the account hook of section 7 replaces them later (H4).

5. Presence across the seam

5.1 The rule

project(translate(p)) == p for every presence a TeamSpeak link reports: translate is LinkSession's old model → v1 entities, project is SessionLink's replica → old model. A unit test checks it on the book fixtures of book.rs (TeamSpeak 3 and 6) and on a generated set of TeamSpeak-shaped presences; the FakeLink tests check it end to end.

5.2 Ids and entities on the TeamSpeak side

Protocol 11.1 "Ids", made concrete for LinkSession:

v1 from the old model
server id 1 (one virtual server per connection)
Server (SERVER(1)) ServerDetails and server_name; uid = ts: + the server uid TsLink computes; host_message_mode, banner, host button, icon (Image{hash: id}), max_members, priority_dim_db, default_role_id = sgid, default_channel_role_id = cgid with bit 62; foreign{system:"teamspeak", kind:"server", json:{"platform", "version"}}, the strings the server sent (F4, F5)
channel id cid; kind: VOICE; position from the order chain (1024 per step); needed{TALK}; icon; banner; max_members (with foreign{"max_clients":0} for a limit of 0, F7)
server chat Channel{id: 1 << 63, kind: SERVER_CHAT} in SERVER(1)
DM channel Channel{id, server_id: 0, kind: DM, recipients: [own user, peer user]} in HOME, made when a message to or from the peer needs it; id has bit 63 set and the FNV-1a 64 hash of the peer's uid in the low 63 bits (1 when they come out 0, so it never equals the server chat's id)
role id sgid (RoleScope::SERVER); cgid with bit 62 (RoleScope::CHANNEL); position = −sort_id; name_mode; kind; icon
user id database_id; a sender with none, or outside our view, gets bit 63 set and the FNV-1a 64 hash of its uid in the low 63 bits
User uid = base64-decoded unique id, uid_kind TS3 (TS6 on a TeamSpeak 6 server); a uid that is not canonical base64 (a ServerQuery client's login name) leaves uid empty and goes into foreign{system:"teamspeak", kind:"user", json:{"uid"}} (F10); name; avatar: Image{hash: avatar MD5, url: myTeamSpeak avatar}; badges; country
Member roles = server groups; channel_roles = {channel: channel group with bit 62}; description; foreign{system:"teamspeak", kind:"client", json:{"icon"}} (F6)
Presence status: IDLE with text = away message when away, else ONLINE
participant id client id; VoiceState{nick, channel_id, slot: client id + 1, self_mute, self_deaf, talker, talk_power, priority_speaker, channel_commander, recording, streaming, kind: QUERY for query clients}
message id per connection: milliseconds since the Unix epoch shifted left by 12 bits, plus a counter in the low 12 bits
rev, epoch one counter per LinkSession from 1; the epoch is new per connection
Mail id the TeamSpeak offline message id

Each inner Presence is diffed against the previous one: changed entities are put, gone ones deleted, one Change per scope. A poke or chat message from someone the snapshot does not hold is preceded by a Change that puts a bare User (synthetic id, uid, name) into LIVE: it shows in no presence (no VoiceState) and lets the engine name the sender (follow-up P5).

5.3 The engine's projection: presence_model and its fix-ups

replica::convert targets the old model already. Where it says less than TsLink does, SessionLink fixes the result up in one module (link/project.rs), each fix with a follow-up for the protocol repository (P6, P7). The old model is TeamSpeak-shaped, and these fix-ups apply the TeamSpeak gateway's id rules of protocol 11.1 so the UI keeps the ids it has; they go when the UI reads the replica (H7).

Fix-up Why
F1 Leave out channels of kind SERVER_CHAT, DM, GROUP_DM, THREAD. presence_model leaves out threads only; the server chat would show as a channel.
F2 On a TeamSpeak backend (backend.product == "teamspeak"), clear bit 62 of RoleScope::CHANNEL role ids (channel groups, ClientInfo.channel_group, ServerDetails.default_channel_group). Today's ids are TeamSpeak's cgids; requests to the gateway and the UI's group lookups use them.
F3 server_key(uid): Server.uid without a leading ts:; used for server_uid and ServerDetails.uid. History rows, aliases and the merge with the gateway and query sources are keyed by today's form. Goes with H5 (and a history key migration).
F4 ServerDetails.version from Server.foreign (teamspeak/server, key version), else Welcome.host.backend.version. server_details leaves it empty by design, and BackendInfo.version is the parsed version, not always the string the server sent.
F5 ServerDetails.platform from Server.foreign (teamspeak/server, key platform). v1 has no field for the server's OS.
F6 ClientInfo.icon from Member.foreign (teamspeak/client, key icon). v1 has no client icon; client_info sets 0.
F7 ChannelInfo.max_clients = Some(0) from Channel.foreign key max_clients. max_members: 0 means unlimited; a TeamSpeak limit of 0 cannot be said.
F8 ClientInfo.talking = Some(talk tracker) where the session offers voice, else None. Talking comes from media (protocol 6.4); client_info sets None.
F9 ClientInfo.streaming = None where the session lacks streams. client_info always gives Some; TeamSpeak 3 reports none.
F10 ClientInfo.uid, a message author's and a poke sender's uid from User.foreign (teamspeak/user, key uid) when User.uid is empty. ServerQuery clients' uids are login names, which User.uid (bytes, base64 for TeamSpeak) cannot hold.

5.4 Normalised fixtures

A TeamSpeak link never reports some states the FakeLink fixtures use; through the adapter they come back normalised, so slice 1 changes the fixture builders, never the assertions (except one, below):

  • sibling channels form an order chain (GAMES.order = LOBBY, not both 0);
  • every client has a database_id, talking: Some(false) and the channel_group it would have (None stays None);
  • presence().server names the server and its uid as TsLink fills them;
  • Talking is played as a voice packet of the talker (LinkEvent::Audio), because the engine derives it from media; the test still expects Event::Talking{client: 8, talking: true};
  • commands_reach_the_link no longer expects the engine's request id (5) in the inner ListFiles: the id the inner link sees is LinkSession's (v1 request ids belong to the session). This is the one changed assertion.

6. Media across the seam

6.1 Voice, engine side

voelin-audio's EncodedVoice/VoicePacket stay what the audio thread speaks; SessionLink frames them in the v1 media codec (voelin_proto::media).

Sending (LinkCmd::Audio): flow FlowId::new(slot, voice_sub::CHANNEL) (the engine has no whisper or priority voice yet), RtpHeader::new(PT_OPUS, seq, timestamp), SSRC = flow; seq counts every packet from 0; timestamp advances by the previous packet's Opus duration (media::opus::packet_ticks, 960 for 20 ms); marker on the first packet of a spurt; EncodedVoice::is_end() becomes an RTP packet with an empty payload, sent once (protocol 6.4 sends it twice; the TeamSpeak side would turn that into two TeamSpeak end packets, so twice waits for H1). MediaClass::Voice.

Receiving (MediaSink::media, never blocking: into the loop's queue): a voice flow is slot → our replica's VoiceState with that slot → TalkerId(participant as u16); sub 1-6 → whisper: true; seq = RTP sequence; payload = RTP payload (empty ends the spurt; VoicePacket::is_end also takes one byte); codec = Music when the Opus TOC has the stereo flag, else Voice. The codec is informational on this path: the jitter buffer decodes every talker with one stereo decoder (jitter.rs), so a frame coded mono inside a music stream decodes the same. Unknown slots are dropped (logged once). The talk tracker sees every voice packet.

6.2 Voice, TeamSpeak side

LinkSession re-wraps, never transcodes (protocol 1.2): an inner VoicePacket becomes RTP on the talker's slot (client id + 1), sub 1 for whispers else 0, seq = TeamSpeak packet id, timestamp from the TOC durations on an unwrapped packet-id counter and wall-clock time across silences, marker after an end or 250 ms of silence, empty payload for the end. Sub 7 (priority voice) is not used: the mixer dims by the presence's priority_speaker flag, as today. Uplink: RTP on our slot loses its header and becomes EncodedVoice{codec: Music if the TOC is stereo else Voice, payload}; the engine encodes VoiceCodec::Voice only (audio.rs), so TeamSpeak keeps receiving Opus Voice. Packets of another slot are NotOwned, over MAX_RTP TooLarge.

6.3 Media classes

Class Used in this half
Voice our voice
StreamAudio, Video, Feedback, Probe not used: TeamSpeak 6 streams are peer to peer, so no stream media crosses a Session (protocol 6.11, 11.1); the SFU path comes with VoelinServer

6.4 Streams: the port now, v1 later

StreamPort is { cmds: UnboundedSender<StreamCmd>, events: UnboundedReceiver<StreamEvent> }, StreamEvent = OwnStream, StreamAudio, StreamAudioEnded; the stream task's bus events go to the engine's bus, its frames to the frames bus (both through LocalCtx). The watched streams' video (StreamFrame) and audio never cross the Session trait in this half.

The v1 mapping the second half implements (H2), per StreamCmd variant:

StreamCmd v1 (peer to peer, what TeamSpeak 6 needs) SFU (VoelinServer, later)
Start{setup, auto_accept} Put Stream{kind, title, mode: P2P, access: OPEN if auto_accept else ASK, viewer_limit, audio, bitrate_kbps}; accessibility and mode 1 in Stream.foreign mode: SFU, layers
Stop Delete Stream{id} same
Respond{viewer, accept} RespondViewer{stream_id, participant_id, accept, offer} (offer from the engine's peer) without offer
Kick{viewer} KickViewer{stream_id, participant_id, reason: KICKED} same
Watch{stream_id} Put Viewer{stream_id, participant_id: P, audio, decodes} same
Leave{stream_id} Delete Viewer (own) same
RequestKeyframe{stream_id} inside the WebRTC peer (PLI) RTCP PLI on FlowId::FEEDBACK (MediaClass::Feedback)
Undecodable{stream_id} renegotiate without the codec (Signal{stream: offer}) Put Viewer{decodes}
WatchLayer{stream_id, layer} Signal{stream: layer} (x-voelin-layer) Put Viewer{max_layer}
Layers(specs) Put Stream{layers} and the local encoders same
LayerFormat{layer, format} local (encoder to peer) local
SrtpProfiles(names) local (peer configuration) n/a
Frame(frame), VideoFrame(frame, format) local (the peer sends them) send_media(Video, RTP on the stream slot, sub = layer)
Friends(clients) local (stream.permissions decides who is admitted) access: FRIENDS on the host
Directory(streams) the gateway daemon's session (protocol 11.2) n/a
Shutdown(reason) local (peer teardown), then close same

And back: OwnStream ← our Stream in LIVE (put, viewer count, delete); StreamAudio ← the peer (SFU: stream slot sub 4, MediaClass::StreamAudio); StreamAudioEnded ← the stream or our Viewer deleted; the bus events StreamsChanged, StreamViewers, StreamViewerRequest (a Viewer in state PENDING), WatchState ← Stream and Viewer entities; StreamLayerBitrate ← the peer's estimate (SFU: Signal{layer_target}).

7. Identity and credentials

  • TeamSpeak identities go as Credential::Foreign{kind: "teamspeak", blob}, blob = the JSON of the KIND_TEAMSPEAK IdentityBlob of the KeyStore (voelin-store keeps tsproto's Identity JSON verbatim). TsConnector parses it back into the tsclientlib::Identity it connects with. No identity in the options (voelinctl without --identity) is an empty blob, and the connector generates one as tsclientlib does today (follow-up P11 writes the convention down).
  • The Voelin key goes as Credential::Voelin(Arc<dyn Signer>): a KIND_VOELIN blob's voelin_key() (IdentityKey implements Signer), or a FileSigner. Nothing uses it in this half (no voelin:// connector), but the conversion is there and tested.
  • The account is a hook: ConnectParams.account is None and issuer_trust Unknown. Backends gets an Option<Arc<dyn AccountAgent>> slot, set by nobody yet. A blob whose binding has custody SERVICE (no local secret) would be Credential::Account{kind: "teamspeak", integration_id}; without an agent the connector fails the connect (its contract in ConnectParams), and the engine reports that as Disconnected. No such blob reaches the engine yet. myTeamSpeak keeps going through TsConnector's watches (4.8) until it moves to AccountAgent::use_integration (myteamspeak.handshake, protocol 13.8; H4).
  • Host trust: TsConnector ignores trust and host_pin (no TLS). The engine passes a HostTrust that refuses until the UI has a TOFU dialog.
  • Slice 1 keeps the API: VoiceOptions.identity is still a tsclientlib::Identity; one function in the TeamSpeak module turns it into the Credential. Slice 3 makes it an IdentityBlob (section 10).

8. Files

The engine owns transfers end to end: progress (files.progress_ms), the .part file and its rename, cancel, resume, the picture limits. The TeamSpeak side only opens the transfer connection, through two inner commands added to LinkCmd in slice 1:

  • OpenRead{file: Remote, offset, reply: oneshot<Result<(u64, BoxRead), String>>}: download_file, then the FileDownload stream and its size go to reply instead of into files::download; FiletransferFailed → Err with the text transfer_error writes today.
  • OpenWrite{file, size, overwrite, resume, reply: oneshot<Result<(u64, BoxWrite), String>>}: upload_file, then the FileUpload stream and its seek_position.

files::download and files::upload take AsyncRead/AsyncWrite instead of TcpStream (their tests keep using TCP). The old Download, Upload and CancelTransfer handling in voice.rs is dead for LinkSession from slice 1 (it never sends them inward) and is deleted in slice 3. Avatars and icons keep their channel-0 paths (/avatar_<uid>, /icon_<id>) as FilePath reads; v1 has them as attachments (H6).

9. Tests

Engine::start_with_link(FakeLink) now wraps the link in LinkSession and drives it through SessionLink, so all seven tests run both translations:

Test What it proves through the adapter
presence_follows_the_link_until_it_disconnects connect sequence and event order, presence round trip, poke, talking from media, notice → Error, Disconnected(Some)
commands_reach_the_link SendChat, Move, SetInputMuted, Poke, ListFiles survive both translations; no streams without the capability; stream commands through StreamPort; replaced link gets Disconnect
a_reconnect_shuts_the_streams_down_before_the_old_connection StreamPort and close share one ordered queue
a_sent_message_and_its_echo_are_one_message our message's Change is today's echo
a_message_that_comes_twice_is_shown_once four Changes, RELAYED flag, dedup in session.rs
history_is_kept_across_the_connection DM channel in HOME, late CHAT subscription, Private(uid) target
a_replaced_connection_is_ignored generation filter with a link that keeps talking after Disconnect

9.2 FakeSession and FakeHost (slice 2)

New tests/session_fake.rs: Engine::start_with_backends with a FakeConnector (scheme fake) registered, VoiceOptions::new("fake://host", ...), the FakeHost filled with Server, VOICE Channels, Roles, Users, Members and VoiceStates through FakeHost::put (it stores what a client cannot set, such as authors), FakeHandle for pushes, media, scripts, held requests and kills. voelin-proto with test-util is a dev-dependency of voelin-core.

link_fake test FakeSession version
presence_follows_the_link_until_it_disconnects host state + JoinVoice (the fake assigns P and slot); Welcome.host.backend set with FakeHost::set_welcome; poke as FakeHandle::push(Signal{poke}); talking by inject_media on alice's slot; Signal{notice} → Error; kill(Network("server shut down")) → "voice: server shut down".
commands_reach_the_link FakeHandle::requests() shows Put{Message}, JoinVoice{password}, the notify (id 0) of self_mute, Signal{poke} (the fake answers signals Ack), and List{FILE} (the fake refuses List.path: scripted with Script::answer("list", ...)). The stream half stays a link test (below).
a_reconnect_shuts_the_streams_down_before_the_old_connection stays a link test: it checks the StreamPort ordering, which a FakeSession has no part in (until H2).
a_sent_message_and_its_echo_are_one_message the fake stores our Put and pushes its Change to CHAT(our channel).
a_message_that_comes_twice_is_shown_once four FakeHost::put(Message), one with MESSAGE_FLAG_RELAYED.
history_is_kept_across_the_connection a DM Channel{server_id: 0} (HOME) and its messages; close and reopen.
a_replaced_connection_is_ignored stays a link test: a closed FakeSession stops pushing, so the stale events cannot be produced on purpose.

New tests the v1 path needs: a connect that fails (FakeConnector::fail_next) → Disconnected(Some(text)); CHAT re-subscription after moving back is a delta (sync.delta); ScopeClosed of CHAT and of LIVE; Rejected answers → RequestDone/Error texts; our voice in FakeHandle::sent_media() (PT 111, SSRC = flow, marker, empty end, sequence); download and upload against the fake's channel files, resume offset from a scripted List; offline messages through scripted Mail answers (the fake does not store Mail); HostUpdate changing the refused features; the conformance suite run against a FakeSession reached through Backends (17 cases, a check that the registry hands the session over untouched).

The link tests that stay (a_reconnect_shuts_the_streams_down..., the stream half of commands_reach_the_link, a_replaced_connection_is_ignored) remain in tests/link_fake.rs in slice 2 and move into the crate in slice 3, when ServerLink is no longer public.

9.3 The conformance suite against the TeamSpeak Session

conformance::run_case with a harness that opens a LinkSession<TsLink> through TsConnector on the dev servers (VOELIN_LIVE=1, TeamSpeak 3 and 6 of dev/docker-compose.yml). The suite's Fixture needs a FakeHandle of the backend; the TeamSpeak server has none, so the harness passes the handle of an unrelated FakeHost and runs only the cases that never touch it:

Case Expected Why
welcome_matches_features passes session only
close_ends_the_session passes session only
a_stale_rev_conflicts_and_a_patch_writes_only_its_paths skipped no chat.edit
requests_apply_in_the_order_they_were_issued skipped no chat.edit
list_pages_history skipped no chat.history (the embedded gateway keeps no history)
idempotency_keys_apply_a_put_once skipped no idempotency
subscribe_syncs_the_scope cannot pass writes to channel 4001, which the server lacks; TeamSpeak channel chat reaches only the own channel
subscribe_resumes_from_a_cursor cannot pass same (4002)
put_answers_entities_and_pushes_the_change_with_the_same_rev cannot pass same (4003)
delete_answers_an_ack_and_pushes_the_removal cannot pass TeamSpeak cannot delete a message; the case needs only chat instead of chat.delete, so it fails instead of skipping (P8)
a_key_names_an_entity_without_its_server cannot pass needs nothing, but creates ScheduledEvent and Emoji, which TeamSpeak lacks (P8)
cancel_before_apply_is_cancelled cannot run holds the backend (FakeHandle::hold)
notifications_are_fire_and_forget cannot run reads the backend's request log; typing goes to channel 1
renew_account_follows_the_feature cannot run changes the backend's features by FakeHandle::push
media_loops_back cannot pass a TeamSpeak server does not return a client's own voice
files_round_trip cannot pass writes an AttachmentSlot; TeamSpeak has channel files, no message attachments; the case needs files instead of chat.attachments (P8)
the_backend_can_end_the_session cannot run FakeHandle::kill; and LinkSession reports a kick as Network(text), not Remote{KICKED}, until H1

What the suite cannot reach is covered by TeamSpeak session tests of their own (live, both servers): an own-channel Put Message answered, then pushed to the other session's CHAT scope and back to ours as a Change (ids agree only with H1's native session); JoinVoice refusal codes (PASSWORD, FULL); a poke Signal between two sessions; voice RTP from one session's slot reaching the other's MediaSink (sequence, marker, end); a channel file written with write_file and read back from an offset with read_file.

10. Slices

Every slice: cargo fmt --all --check; cargo clippy $(scripts/own-crates.sh) --all-targets --no-deps --locked -- -D warnings; cargo test -p voelin-core --locked (also --features media), the tests of every crate the slice touches; cargo check --workspace --locked; cargo deny --locked check; scripts/notices.sh with THIRD_PARTY_NOTICES.md regenerated whenever Cargo.lock changes; docs on new public items; the live tests and scripts/it-smoke.sh engine scenarios against the TeamSpeak dev servers (this repository's dev/docker-compose.yml, the same as VoelinGateWay's) with the results compared to the baseline. One commit per step is fine; no history rewrite.

Slice 0 (precondition): baseline

On main (59fec5b), before any code: VOELIN_LIVE=1 cargo test -p voelin-core --features media-desktop --test live --test voice_features --test stream_live --test media_live, and scripts/it-smoke.sh ts3 ts6. Record which pass, which fail and why: the plan notes they have not run since Phase 4 step 1, and slice 1's "no behaviour change" is measured against this record, not against an assumption.

Slice 1: the adapter

  1. Protocol crates at one revision. voelin-identity, voelin-proto and voelin-model from VoelinProtocol at one rev (main c8e0e5a or later: it has AccountAgent, IssuerTrust, Credential::Account; voelin-identity changed only in cert.rs and revocation.rs since 64808cc). crates/voelin-model is removed and every crate that used it takes voelin-model = { workspace = true } (voelin-core, -ui, -gateway, -gateway-proto, -observer, -android, voelinctl: a one-line manifest change each, the UI's being a compile fix); the [patch] recipe of docs/building.md gains voelin-model. Acceptance: whole workspace builds, all tests green, no source change besides manifests. Of the model crate's files only lib.rs (two more modules, perms and replica) and badges.rs, link.rs, tree.rs (a doc comment and two equivalent expressions) differ.
  2. The seam. link/ (Backends, SessionLink, project, media), ts_session.rs (LinkSession, TsConnector, LinkConnector for start_with_link), OpenRead/OpenWrite in voice.rs, files.rs generic, Engine::start_with_backends. Acceptance:
    • git diff main -- crates/voelin-core/src/session.rs is empty;
    • the seven tests of tests/link_fake.rs pass through the adapter with only the fixture changes of 5.4;
    • unit tests: the presence round trip of 5.1 (book fixtures and generated presences), LinkCmd → v1 → inner LinkCmd for every row of table 3.1 with a recording link, v1 media framing both ways (sequence, marker, end, whisper, TOC codec), talk tracker timing (400 ms), the close table of 4.5, the error texts of 4.6, the backend and capability tables of 4.7;
    • live tests and smoke scenarios: no result worse than the baseline (section 0), in particular engine_voice_check (files, avatar, poke, private and offline messages, friend online, blocked poke), voice round trip, the TeamSpeak 6 stream scenarios;
    • rg -n 'tsclientlib|tsproto|voelin_query' over the new Session-facing modules (link/backends.rs, link/session_link.rs, link/project.rs, link/media.rs) is empty; TeamSpeak types appear only in ts_session.rs and the files that had them before (link/mod.rs keeps ConnectOptions and LinkCtx until slice 3). No public item is removed in this slice.

Slice 2: tests on FakeSession and FakeHost

  • tests/session_fake.rs as in 9.2, the conformance run through Backends (17 of 17), the live TeamSpeak conformance subset of 9.3 with the expected verdicts asserted per case (2 pass, 4 skipped, the rest not run, each with the reason of the table in a comment), and the TeamSpeak session tests of 9.3.
  • tests/link_fake.rs keeps only the three link tests named in 9.2.
  • Acceptance: all of it green on both dev servers; a deliberately broken translation (for instance a dropped self_mute path) makes a session_fake test fail, shown once in the report.
  • ServerLink, TsLink, Engine::start_with_link, LinkCtx, LinkCmd, LinkEvent and Remote are no longer public (the engine keeps LinkCmd and LinkEvent as session.rs's private vocabulary; the TeamSpeak module keeps the inner trait). The remaining link tests become unit tests in the crate.
  • src/ts/ holds the TeamSpeak implementation: ts_link.rs, voice.rs, book.rs, ts_session.rs, versions.rs, identity.rs (moved with history). Public as voelin_core::ts: TsConnector (with set_myts_identity and set_myts_data), versions, identity. This module is what moves to VoelinGateWay.
  • VoiceOptions (no longer an alias of ConnectOptions): identity: Option<IdentityBlob>, client_version: Option<String> (a spec for ts::versions::resolve, passed to TsConnector as the link parameter client_version; Link::parse ignores unknown keys), stream_peer: PeerConfig, the rest unchanged.
  • Command::SetMytsIdentity and SetMytsData removed (nothing sends them; TsConnector's setters replace them). ObserveGateway.identity becomes a Box<IdentityBlob> (gateway.rs parses it); ObserveQuery.connect becomes a core-owned QueryLogin (transport, address, user, secret, server port, server id) that query.rs turns into voelin_query::Connect. The public gateway::connect(url, identity) takes the blob too (nothing outside the crate calls it today).
  • voice.rs loses Download, Upload, CancelTransfer; the picture limits live in SessionLink only.
  • docs/architecture.md: "The server link" becomes "The session seam" (registry, SessionLink, the TeamSpeak module, StreamPort, the fix-ups of 5.3, what is still TeamSpeak-shaped: u16 client ids and the old model); the crate table row of voelin-core follows; this document's status line.
  • CHANGELOG.md: it lists user-visible changes only. An entry under "Changed" only if a difference against the baseline remains visible (none is intended); the reviewer confirms none was needed.
  • UI and voelinctl: compile fixes only (identity blob instead of tsclientlib::Identity, the spec string for client_version, voelin_core::ts::{versions, identity} paths, QueryLogin).
  • Acceptance:
    • rg -n 'tsclientlib|tsproto|voelin_query' crates/voelin-core/src --glob '!ts/**' --glob '!gateway.rs' --glob '!query.rs' --glob '!stream.rs' is empty, and the four exceptions use them privately: gateway.rs and query.rs are the two observer sources (H5), stream.rs is the TeamSpeak 6 stream task behind StreamPort (H2, H3);
    • session.rs names no TeamSpeak crate;
    • no public item outside voelin_core::ts names a type of tsclientlib, tsproto* or voelin-query (checked with cargo doc and a grep of pub items); voelin_core::stream still re-exports the WebRTC peer types of voelin-stream (PeerConfig, MediaFrame, MediaKind, MediaTime, Frequency, VideoFormat, VideoCodec, Codec, FrameSource, SyntheticSource): they belong to the peer, which protocol 6.11 and 11.1 keep in the client, and land in a crate of their own when voelin-stream is split (H3);
    • cargo tree -p voelin-core -e normal | grep -E 'tsclientlib|tsproto' may still list them (the TeamSpeak module is still in the crate);
    • all of slice 1's and slice 2's checks, live tests and smoke included.

11. Follow-ups

11.1 For the protocol repository (seam, schema, model, suite)

Nothing here blocks this half: each has a workaround above.

# What Workaround meanwhile
P1 Hello has no initial voice channel (path or id, password) for backends that seat a client at connect; a Voelin host could also take it to save the JoinVoice round trip. ts3server:// link parameters channel/cid, channelpassword (4.2).
P2 Write down that the first JoinVoice of a session that its backend seated at connect answers the seat without moving (11.1). LinkSession does it.
P3 A host with several servers: the address (or Welcome) should name the one to use. List{SERVER}, the only or lowest one.
P4 write_file should answer the offset the backend appends at (Upload.offset), so a resume needs no List. List{FILE} before a resumed upload; CONFLICT on a mismatch.
P5 No sender name or uid for a Signal (poke) or message author outside the receiver's view (hidden ServerQuery clients). A bare User with a synthetic id before the signal (5.2).
P6 Schema gaps of TeamSpeak presence: a client icon, a channel limit of 0, the server's platform and version string as sent, a uid that is no byte string (ServerQuery login names). Foreign keys icon, max_clients, platform, version, uid (F4-F7, F10).
P7 replica::convert: SERVER_CHAT and DM channels in presence_model; the per-server TeamSpeak avatar read from User.avatar instead of Member.avatar; streaming: Some(false) without the feature; empty version; channel role ids not given back; client icon 0; talking always None. Fix-ups F1-F10.
P8 Conformance suite: a backend driver trait (hold, release, kill, push, request log) instead of FakeHandle, so backend-driven cases run on any backend; chat channel and server chosen by the harness instead of 4001-4020; needs fixed (chat.delete for the delete case; events and emoji for a_key_names_...; chat.attachments or a FilePath variant for files_round_trip); a two-session media_loops_back for backends that do not loop back. The subset of 9.3 and TeamSpeak tests of our own.
P9 FakeHost files no Server stub or own Member in HOME (protocol 5.2). List{SERVER} (4.2).
P10 ServerQuery capabilities (raw, SSH, HTTP) have no feature string. From the flavor (4.7); they leave with the observer (H5).
P11 Protocol 11.1 could name Hello.invite_code ↔ client_default_token (privilege keys), and section 13.8 the empty Credential::Foreign blob as "generate an identity". Done that way here.

11.2 The second half (TeamSpeak Session to VoelinGateWay)

# What
H1 A native TeamSpeak Session replaces LinkSession<TsLink>: voice.rs speaks v1 (book → entities without the old model, notifications → Changes), real answers for chat and pokes (read-your-writes, errors on the request), a kick as Remote{KICKED}, tsclientlib's own reconnect as a new epoch and a full resync, ping and loss in LinkStats, whispers (sub 1-6), priority voice (sub 7), typing, the end of a spurt sent twice collapsed to one TeamSpeak packet, every TeamSpeak feature of protocol 9.1.
H2 Streams on v1: the stream task's WebRTC peer moves to the engine and speaks Stream/Viewer/RespondViewer/KickViewer/Signal{stream} (table 6.4); the TeamSpeak session translates TeamSpeak 6's stream commands (setupstream, joinstreamrequest, respondjoinstreamrequest, removeclientfromstream, streamsignaling, the notifications); StreamPort and LocalConnector's stream part go.
H3 voelin-stream split rather than inverted: the TeamSpeak 6 signalling (commands, notifications, signal JSON) goes to VoelinGateWay with the TeamSpeak session; the str0m peer with PeerConfig, MediaFrame, VideoFormat, codecs and simulcast stays client side (with voelin-media, or a crate of its own), because protocol 6.11 and 11.1 put the peer in the client. Then nothing in VoelinGateWay depends on voelin-media, and the cycle the plan worries about cannot form.
H4 myTeamSpeak through AccountAgent (myteamspeak.handshake with the 32-byte digest, the presentation, sign-out clearing, protocol 13.8) instead of TsConnector's watches; Credential::Account for custody SERVICE identities.
H5 The gateway (tsgw) and query sources become a second Session to a gateway daemon (protocol 11.2); then F3's ts: rule (with a history key migration) and the query capabilities go.
H6 Avatars and icons as attachments (Image.attachment_id, content-addressed cache) instead of channel-0 paths.
H7 The UI on the replica (Phase 5): the old-model projection and F1-F10 go; u16 client ids widen to u32 participants.
H8 Reconnect with backoff, resume tokens and persisted cursors move to voelin-sdk once it exists; the engine consumes the SDK.
H9 Move src/ts/ (with its live tests) to voelin-gateway-ts (features basic, streams), first behind a ts feature of voelin-core, then by git tag; the exit check of plan step 6, cargo tree -p voelin-core -e normal | grep -E 'tsclientlib|tsproto' empty, holds after H1-H3 and this.

11.3 Coordination

  • phase5/ui-vm adds crates/voelin-ui-vm and moves UI logic (servers, settings) into it. Slice 1's model switch needs its manifest on voelin-model.workspace = true; slice 3's API changes (identity blob, client_version spec, ts:: paths, QueryLogin) need compile fixes where that branch moved VoiceOptions and ObserveQuery construction. Merge phase5/ui-vm before slice 3, or plan the fixes on top of it.
  • Branches that still edit crates/voelin-model must make those changes in VoelinProtocol after slice 1.

12. Risks

Risk Mitigation
A presence field gets lost between the two translations (a UI detail disappears). Round-trip tests on the book fixtures and generated presences; F1-F10 listed; live smoke against the baseline.
Event timing changes: Connected now follows three syncs and a JoinVoice; snapshots are coalesced. All in process for TeamSpeak (microseconds); the FakeLink tests pin the order; session.rs is unchanged.
The inner bus of LinkSession lags and a request never gets its answer. Capacity 4096, a timeout on every pending request, lag logged.
The consumer of the push channel lags and stalls the voice and the commands that share the task. The task never waits on the channel: what does not fit is dropped and the scope is sent again whole when there is room (14).
A uid that round-trips through User.uid on one side and through Foreign on the other (F10) would key contacts and private history differently. Both sides use one rule (canonical base64 → bytes, anything else → Foreign), asserted by the round-trip test on TeamSpeak 3 and 6 uids, ServerQuery login names and the FakeLink fixtures' alice=; checked live (contacts and private history keyed by uid).
The model crate switch collides with other branches. 11.3; the switch is manifest-only.
Two adapters cost CPU per voice packet (RTP wrap and unwrap in process). About a hundred bytes copied per 20 ms per talker; measured in slice 1 by a unit test (a_voice_packet_costs_microseconds_through_both_adapters, section 13).

13. Slice 1 as implemented

Slice 1 (the adapter, section 10) is in phase4/session-seam: step 1 is the commit that takes voelin-model from the protocol repository, step 2 the commit that puts the engine on the Session. session.rs is unchanged (git diff 59fec5b -- crates/voelin-core/src/session.rs is empty), and no public item was removed. Where the code differs from the text above:

  • Files. ts_session is a directory (mod.rs with LinkConnector, TsConnector, connect_params and the Session impl; driver.rs, the task that plays the host; entities.rs, the presence as v1 entities and its diff; ids.rs; media.rs, voice as RTP and back). The unit tests of the mapping are link/tests.rs; the presence round trip is in book.rs, next to the book fixtures. bytes is a direct dependency now (the RTP packets of MediaPacket).
  • LinkSession is not generic. It holds the inner link as an Arc<dyn ServerLink>; LinkConnector::new(link, schemes) and LinkConnector::any(link) are the generic part, and TsConnector is a LinkConnector over TsLink for ts3server and teamspeak.
  • The account-proof watches (myts_identity, myts_data) travel in LocalCtx, from the engine's LinkCtx to the connection, not in TsConnector (section 4.8): Engine::start_with_backends takes a registry that is made before the engine exists, so the watches cannot be handed to a connector in it. LocalCtx::standalone() makes a context (with the watches' senders kept alive) for a connector called outside an engine; the plain Connector::connect of LinkConnector uses it.
  • OpenWrite hands a connection, not a write half (BoxDuplex): the upload's done has to see the server close it. UploadBody reports the shutdown of the body to done, which then waits for the end of the connection (30 s at most), as files::upload always did.
  • Media before pushes. SessionLink's loop polls the media queue before the pushes (section 4.2 says the reverse): the in-process task writes a talker's VoiceState before its first packet, but nothing orders a push and a media packet across two channels, and the fake-link tests play Audio, Poke and Error in one go and wait for the events in that order. A packet from a slot the replica does not know yet fetches the queued pushes first and tries again, so a talker's first packet is not lost either way.
  • The stream task's reports wait for the engine's announcement. The TeamSpeak 6 stream task puts Event::StreamsChanged and the like on the engine's bus itself. Behind a session the engine learns of the connection only after the connect sequence (a few requests through the driver), while the stream task lists the server's streams as soon as the server tells it; a client that acts on the first list (voelinctl gateway --engine --watch-streamer, the directory_check of scripts/it-smoke.sh) sent WatchStream before the engine knew it had voice, and failed with not connected with voice in half of the runs (3 of 6; the baseline binary passed all 4 runs the server's clone limit did not end first, the two alternating on one TeamSpeak 6 server). The driver of ts_session therefore holds the stream task's bus events back (Held in ts_session/driver.rs; only for a link with streams, and only the events that are no answer to a request) until the engine's first stream command, which session.rs sends in its handling of Connected right after it has emitted the state, or for 3 seconds. Three unit tests pin it (link/tests.rs: held until the first stream command, not held for ever, not held for a link without streams); the same probe passes 8 of 8 with it.
  • CHAT scopes are re-subscribed in full. The replica drops a scope's cursor and entities when it is unsubscribed and refuses a delta sync without a baseline, so SessionLink does not keep cursors for a delta after moving back (section 4.3); the full sync repeats the window and the engine's seen set reports each (channel, id) once. LinkSession does answer Subscribe.since of its own epoch with a delta.
  • Fixtures (section 5.4), beyond the builders listed there: presence() gives the own client the unique id the Connected event names and the server the version of the backend; in a_replaced_connection_is_ignored the new connection's presence puts the own client in the lobby, where its OwnChannel and its channel chat are (a TeamSpeak server delivers channel chat for the channel we are in only, section 4.3). In the book round trip a TeamSpeak 6 client with no streaming flag in the book comes back as Some(false) (v1 has no "unknown").
  • Known limits. Two clients with one identity (one database id) are two users of the replica (the own client keeps the database id, else the lower client id; the other gets a user id made of its client id). A Put Message before any snapshot is handed to the link whatever the channel. Welcome.limits is partly filled. Backends has a slot for an AccountAgent and for a HostTrust (refusing by default); nothing sets either yet.

Follow-ups for the protocol repository, found while writing the code:

  • P12. FileEntry.from_path should say whether it includes the file's name. The TeamSpeak side reads it as the whole old path (/dir/name), with path and name of the entry the new place.
  • P13. Signal{speaking} is for talking in channels the user is not in (protocol 5.6, 6.4). A host that hears a talker in our own channel and does not carry the voice as media (TeamSpeak's Speex and CELT talkers) has no way to say so but that signal, which LinkSession uses for them (SessionLink believes it until on: false). The protocol should say that the signal may do this, or give such a talker a flag on the VoiceState.
  • P14. Say what a backend that reconnects inside a session (TeamSpeak's tsclientlib) tells its consumer: today the participant id of the session changes without a word, and a consumer has to find itself again by its user. A Change that puts the new VoiceState and deletes the old one is all there is; the native session of H1 starts a new epoch instead.

What ran against the baseline (main 59fec5b; the dev servers of dev/docker-compose.yml as the compose project voelin-seam, TeamSpeak 3.13.8 and 6.0.0-beta13.1):

Check Baseline Adapter
scripts/it-smoke.sh ts3 ts6, every per-server scenario (connect and tree, server and channel chat, voice tone, invisible presence, relay chat, gateway, history, pins and reactions, streams and late and elsewhere streams on TS6, the engine's voice features: file upload, link, list, download and delete; avatar; poke; private and offline messages; friend; blocked poke) all pass all pass, the same output apart from counters and ids (the run before the fix of the stream reports, above, failed directory_check)
the script's last stage, cargo test -p voelin-core --features media-desktop --test live --test stream_live --test media_live (parallel) 5 pass, ts6_banners fails (4 HTTP requests where 0 are expected: another test's engine shares the mock server) the same
live (serial, --test-threads=1) 6 of 6 6 of 6
voice_features, stream_live, media_live (serial) 3, 3, 2 pass 3, 3, 2 pass

cargo test -p voelin-core has two failures that exist on the baseline too (discover::tests::without_records_the_gateway_itself_is_asked, web::tests::pictures_go_through_the_proxy_named_for_each_hop: both reach a server bound to 127.0.0.1 through the name localhost, which resolves to ::1 only on the machine the tests ran on; the modules are unchanged).

The CPU cost of the second adapter per voice packet (section 12) is measured by the unit test a_voice_packet_costs_microseconds_through_both_adapters (link/tests.rs): 5,000 Opus packets of 20 ms each way through both adapters and the recording link, in a debug build, took about 7 microseconds per packet to the host and 10 microseconds from it. At one talker that is well under a tenth of a percent of a core; the test bounds each direction at 500 microseconds. tests/session_backends.rs adds two integration tests: the engine over the protocol repository's FakeConnector through Engine::start_with_backends (connect, the server's name, the channels, a move, disconnect), and the registry's error text for an address no connector serves.

14. Review round 2 of slice 1

The review of the first implementation found eight defects; each is fixed in its own place above and tested.

Finding Fix Test
Chat messages of a CHAT scope's initial full sync were lost when SyncBegin and Change were in one batch and SyncEnd in the next: (channel, id) was marked as reported before the replica could show the message. A message is marked as reported only when it was shown; at the SyncEnd of a CHAT scope the messages of that channel not shown yet are (4.3). the_messages_of_a_chat_sync_are_reported_when_the_sync_ends, a_message_that_comes_before_its_scope_is_reported_with_the_sync (link/session_link.rs)
The own client id was pinned for the connection: after tsclientlib's reconnect (a new client id) OwnChannel and the own channel's chat stopped. Both sides find us again by our unique id and user (4.4); the own client keeps the database id of an identity that is there twice. the_engine_follows_a_reconnect_that_makes_us_another_client, we_stay_the_client_we_were_while_it_is_there, the_own_client_keeps_the_database_id_of_an_identity_that_is_there_twice
CHAT subscriptions were capped at 16 in process: the 15th private peer's messages were never delivered. LinkSession says 65,536; SessionLink sizes its scopes from Welcome.limits (16 only when the host says nothing), server chat and own channel first, newest private conversations next (4.3). private_messages_from_more_than_16_peers_all_arrive, the limits in the_welcome_names_the_host_the_user_and_what_the_link_can_do
LinkSession::notify accepted List, FileRead and FileWrite and ignored them. A misplaced op is a Protocol error; any other op of the control stream is run (3.1). a_notify_needs_the_control_stream_and_is_run_as_the_request_it_is
A push channel that ended during the connect syncs threw the session's close reason away. The reason of closed() is the reason of Disconnected (4.2). a_session_that_ends_during_the_connect_syncs_says_why
LinkSession awaited pushes.send(): a lagging consumer stalled voice and commands. Nothing in the task waits: a push that finds the channel full is dropped, the scope is marked as lagged and sent again whole (SyncBegin..SyncEnd, all or none) when the channel has room, as ConnectParams.push_capacity documents; a scope bigger than the channel is sent in bigger chunks, so that it fits an empty channel. Signals have no scope: they are dropped. a_consumer_that_lags_loses_the_queue_and_gets_the_scope_again, a_scope_bigger_than_the_channel_is_sent_in_bigger_chunks
An address no connector serves was echoed in full, with ?channelpassword=. The text cuts the address at ? and # (4.1). the_text_of_an_address_nobody_serves_keeps_the_channel_password_out, an_address_is_shown_without_its_secrets
LinkEvent::Talking of the inner link was ignored, and its documentation unchanged: Speex and CELT talkers were no longer shown as talking. The docs of Talking, OwnChannel and Connected.own_client say what the adapter derives; the inner link's Talking goes on as Signal{speaking}, a hint that SessionLink believes until it is over (P13). a_talker_the_link_hears_but_does_not_forward_is_shown_as_talking, a_host_that_says_someone_talks_is_believed_until_it_says_otherwise