Skip to content

feat(websocket): accept additional handshake headers in WebSocketOptions - #186

Merged
lumpinif merged 12 commits into
mainfrom
feat/ws-additional-headers
Dec 1, 2026
Merged

lumpinif merged 12 commits into
mainfrom
feat/ws-additional-headers

Conversation

@lumpinif

@lumpinif lumpinif commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Replaces #184. That design added a second propagation mechanism inside the SDK, with its own rules, defaults and warning. This one relies on the caller's httpx client and instrumentation, which already reach every path, and adds the one missing per-call input.

Problem

On main, a caller can add a header to one HTTP call (RequestOptions(additional_headers=...)) but not to one WebSocket call: WebSocketOptions has no header input, and WebSocketOptions(additional_headers=...) raises TypeError. Without OpenTelemetry, the only way to send a traceparent on the tts.stream_websocket or asr.stream_websocket handshake is a custom httpx_client. With opentelemetry-instrumentation-httpx and a tracer provider configured, HTTP calls and both handshakes already carry the trace on main; the tracing tests that do not use the new option pass there.

Change

  • WebSocketOptions(additional_headers: Optional[dict[str, str]] = None). The headers are sent on the handshake of tts.stream_websocket and asr.stream_websocket, sync and async.
  • The headers are merged as RequestOptions.additional_headers are on an HTTP call: an Authorization given here, in any casing, replaces the API key and is sent once; a User-Agent is appended to the SDK's own and sent once, the last one when two spellings are given. model is always the method's argument; a model given here, in any casing, is ignored. An Authorization on a supplied httpx_client does not replace the key. The caller's dict is not modified, and the field is not passed to httpx-ws.
  • README: a short "Tracing" section. WebSocketOptions docstring updated.

Public interface

  • New keyword argument and attribute additional_headers on WebSocketOptions. Nothing else: no new class, function, export or exception, and no signature change on stream_websocket.

Behaviour changes

Before After
Handshake of a caller who does not use the field, on all four paths Authorization, model, User-Agent and what httpx and httpx-ws add unchanged: the same header names, values and order
WebSocketOptions(additional_headers=...) TypeError the headers are sent on the handshake

One rule in the three SDKs

A per-call Authorization replaces the API key on every transport: on an HTTP call (as on main) and now on the WebSocket handshakes. A client-level one (here: on a supplied httpx_client) does not. model on a handshake is the method's argument. typescript#20 and go#26 follow the same rule. The per-call handshake input is new in this PR, so nothing changes for existing callers.

Carrying a trace

Use one way. With OpenTelemetry, configure a tracer provider and enable opentelemetry-instrumentation-httpx: HTTP calls and both handshakes carry the current trace id, under a client span that the instrumentation creates. A WebSocket stream connects on its first iteration, so iterate it inside the span. Without OpenTelemetry, pass traceparent in RequestOptions on HTTP calls and in WebSocketOptions.additional_headers on WebSocket calls, or give the client an httpx_client with a request event hook; a client you pass in keeps its own settings, so the README's example sets its timeout. A traceparent that the instrumentation sends replaces one set by hand; with no tracer provider it sends none and the hand-set one goes out as it is.

Not in this change

No header provider, no default OpenTelemetry behaviour, no runtime dependency, no validation, no warning, no new exception. A header value httpx rejects raises httpx's own error. fish_audio_sdk is unchanged.

Tests

All against the local WebSocket and HTTP test servers. The WebSocket server records the handshake's headers as its parser reports them: names in lower case, in order, repeated names kept.

  • test_websocket_headers.py (each on the four WebSocket paths): the headers are sent and the dict is not changed; an AUTHORIZATION replaces the API key and is sent once; a Model does not replace the method's model; an Authorization on a supplied httpx_client does not replace the key; a user-agent is appended to the SDK's, the last of two spellings when both are given; default options send the same header names as no options; the default handshake's header names in order, and the values of authorization, model and user-agent, are written out.
  • test_tracing.py, with the real opentelemetry-instrumentation-httpx (dev dependency only) and a tracer provider: under an active span, tts.convert, asr.transcribe (sync and async) and the four handshakes each carry exactly one traceparent with the span's trace id; the four handshakes and tts.convert are checked to be sent under a span of their own; a stream created inside the span but iterated after it ends gets a different trace id; a hand-set traceparent is replaced on an HTTP call and on the four handshakes, and without a tracer provider it is sent as it is; a request event hook (async hook for the async client) adds its header to the HTTP calls and both handshakes.

poe check and poe test pass with main merged in.

Live run against production

Sync and async, each of tts.convert, asr.transcribe, tts.stream_websocket and asr.stream_websocket returned x-fish-trace-id equal to the expected trace id: (a) with opentelemetry-instrumentation-httpx and an active span, (b) without OpenTelemetry, with RequestOptions and WebSocketOptions(additional_headers={"traceparent": ...}), (c) with the README's event-hook client. 24 of 24 matched.

Summary by CodeRabbit

  • New Features
    • WebSocket connections support custom handshake headers. Custom authorization headers replace the SDK key, while custom User-Agent values are appended to the SDK value.
    • Trace headers can be propagated through HTTP requests and WebSocket handshakes using OpenTelemetry, per-call options, or an HTTP request hook.
  • Bug Fixes
    • Additional query parameters are included in requests and combined with method-level parameters when both are provided. Authorization headers with different capitalization are handled consistently.
  • Documentation
    • Added guidance on tracing setup, header handling, caller-provided HTTP clients, and when WebSocket streams connect.

WebSocketOptions.additional_headers adds headers to the handshake of
tts.stream_websocket and asr.stream_websocket, sync and async, so a caller
without OpenTelemetry can send a traceparent on a single WebSocket call as
RequestOptions already allows on HTTP. The SDK's own Authorization,
User-Agent and model headers are kept whatever the casing of a name given.

The README gains a Tracing section: opentelemetry-instrumentation-httpx
covers HTTP and both handshakes; without it, use the per-call options or
an httpx_client with a request event hook.
@lumpinif
lumpinif requested review from abersheeran and a lite review from Copilot November 26, 2026 11:04
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-26T11:04:02.773811Z
We couldn’t complete this review. Comment @codex review to try again.
40eb257 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The SDK now accepts additional headers for WebSocket handshakes and applies shared header rules when building them. The README documents OpenTelemetry and manual trace propagation for HTTP calls and WebSocket handshakes. Tests cover header handling and trace propagation.

Changes: Header and Trace Propagation

Layer / File(s) Summary
Additional header contract and merge rules
src/fishaudio/core/websocket_options.py, src/fishaudio/core/client_wrapper.py, tests/unit/test_core.py
WebSocketOptions accepts additional headers. Shared header logic handles case-insensitive authorization and user-agent names, with the last supplied value taking precedence.
WebSocket handshake integration
src/fishaudio/resources/asr.py, src/fishaudio/resources/tts.py, tests/unit/realtime_server.py, tests/unit/test_websocket_headers.py
Sync and async ASR and TTS paths use the shared handshake-header logic. Tests cover header values, casing conflicts, model selection, supplied clients, and input mapping preservation.
Trace propagation coverage and guidance
tests/unit/test_tracing.py, README.md, pyproject.toml
Tests check trace propagation through instrumented HTTP calls, WebSocket handshakes, and HTTPX request hooks. The README documents these approaches, and the development dependencies add OpenTelemetry packages.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Feature

Suggested reviewers: leng-yue

Merge Risk: Minimal · up to 98bf7 · assessed changes only

Path filters excluded changed files. This rating applies only to the assessed changes.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: WebSocketOptions gains an additional_headers field that lets callers pass extra handshake headers to the TTS and ASR stream_websocket methods. The feat(websocket) pref…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: WebSocketOptions gains an additional_headers field that lets callers pass extra handshake headers to the TTS and ASR stream_websocket methods. The feat(websocket) prefix matches the changeset, and the title is concise and specific. The title does not mention tracing docs or the test additions, which is expected because they are secondary.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 14e0ddf2-f59f-49a9-b2ff-1b601f7e4acc
Commits

Reviewing files that changed from the base of the PR and between a612be6 and 98bf75b.

Files selected for processing: 1

  • tests/unit/test_core.py

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
src/fishaudio/core/client_wrapper.py 97.81% <100.00%> (+3.29%) ⬆️
src/fishaudio/core/websocket_options.py 100.00% <100.00%> (ø)
src/fishaudio/resources/asr.py 100.00% <100.00%> (ø)
src/fishaudio/resources/tts.py 96.63% <100.00%> (+0.04%) ⬆️

... and 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues are reported, and the changes include targeted coverage for custom WebSocket headers, precedence, immutability, and tracing across synchronous and asynchronous paths.

No open issues 🎉

What changed in this PR

Adds per-call custom headers to WebSocketOptions, enabling tracing and other caller-supplied metadata on synchronous and asynchronous TTS and ASR WebSocket handshakes while preserving SDK-managed header precedence.

Changes:

  • Adds and documents WebSocketOptions.additional_headers with case-insensitive SDK header precedence.
  • Adds WebSocket header, tracing, and request-hook integration coverage across HTTP and WebSocket paths.
  • Updates tracing documentation and development dependencies.
File Description
uv.lock Locks the updated SDK metadata and new OpenTelemetry development dependencies.
tests/​unit/​test_websocket_headers.py Tests WebSocket header delivery, immutability, SDK header precedence, and default behavior.
tests/​unit/​test_tracing.py Tests OpenTelemetry and request-hook trace propagation across HTTP and WebSocket calls.
tests/​unit/​realtime_server.py Extends the local test server to record handshake headers and support WebSocket path testing.
src/​fishaudio/​resources/​tts.py Applies additional headers to synchronous and asynchronous TTS WebSocket handshakes.
src/​fishaudio/​resources/​asr.py Applies additional headers to synchronous and asynchronous ASR WebSocket handshakes.
src/​fishaudio/​core/​websocket_options.py Adds and documents the per-call additional_headers WebSocket option.
README.md Documents OpenTelemetry, explicit traceparent, and httpx event-hook tracing approaches.
pyproject.toml Adds OpenTelemetry instrumentation and SDK packages as development dependencies.

Review effort: Lite

…s own

A User-Agent given in WebSocketOptions.additional_headers was replaced by
the SDK's. It is now appended, as on HTTP calls, on all four handshakes.
…eeds

The README's event-hook client had httpx's 5 s timeout. The tracing note
now says a tracer provider is needed and when a hand-set traceparent is
replaced; tests pin both. The handshake helper is private, and the test
server's comments say what it records.
…re merged

An Authorization in WebSocketOptions.additional_headers now replaces the
API key on the handshake, as one in RequestOptions does on an HTTP call.
The handshake's model stays the method's argument. One on a supplied
httpx client still does not replace the key. additional_headers is new
in this branch, so nothing changes for existing callers.
get_headers() replaced the SDK's Authorization with the caller's but kept
every spelling the caller gave, so {"Authorization": a, "authorization": b}
was sent as two Authorization headers on HTTP calls and on the WebSocket
handshake. The last one given is now sent, as for User-Agent.
Codecov's patch check counted the query-params block of
_prepare_request_kwargs as new lines once main had moved it; no test
had ever run it. Cover it with and without method params.
@lumpinif
lumpinif merged commit 5b364b6 into main Dec 1, 2026
27 checks passed
@lumpinif
lumpinif deleted the feat/ws-additional-headers branch December 1, 2026 12:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants