diff --git a/src/client/RELEASE_AND_DEPLOYMENT.md b/src/client/RELEASE_AND_DEPLOYMENT.md new file mode 100644 index 000000000..ec5965a2a --- /dev/null +++ b/src/client/RELEASE_AND_DEPLOYMENT.md @@ -0,0 +1,283 @@ +# Independent release and deployment guide + +This guide creates and deploys the five new artifacts around an existing +`sparkd` deployment. It deliberately does not create one shared Compose stack. +Each owning team can build, publish, deploy, restart, and roll back its component +without rebuilding the others. + +## Chosen deployment model + +| Component | Release artifact | Deployment unit | +| --- | --- | --- | +| `sparkd` | Existing Spark artifact/image | Existing Spark scripts; unchanged | +| Spark command bridge | Self-contained Linux tarball | Independent `systemd` service | +| BlueOrb RSS | Self-contained Linux tarball | Independent `systemd` service | +| `blueorb-surface-python` | Python wheel and source distribution | Published library consumed by clients | +| `spark-command-client` | Python wheel and source distribution | Published library consumed by the gateway | +| `spark-public-websocket` | Python wheel and source distribution | Independent virtual environment and `systemd` service | + +The .NET tarballs are self-contained: the target host does not need the .NET +runtime. They are directories rather than single-file executables because both +services may carry native libraries. The Python gateway receives its two client +libraries as wheels and has no source-level dependency on either backend. + +Every component uses its own semantic version. Record the compatible set for an +environment using [`deploy/release-manifest.env.example`](deploy/release-manifest.env.example). +Do not infer compatibility from matching version numbers. + +## Build prerequisites + +- Linux x86-64 build host for `linux-x64` artifacts. +- .NET 8 SDK matching each repository's `global.json`. +- Python 3.10 or newer. +- `python -m pip install build` in the release-build environment. +- `tar` and `sha256sum`. +- Access to the released `Bts.Spark.Sdk` NuGet packages. + +Build from clean, reviewed commits. Tags should use the owning component name, +for example `spark-command-bridge/v0.1.0` rather than one repository-wide tag. + +## 1. Build `blueorb-surface-python` + +The version comes from `/home/bts/blueorb/BlueOrb.Surface.Python/pyproject.toml`. +Bump that value before creating a new release. + +```sh +cd /home/bts/blueorb/BlueOrb.Surface.Python +PYTHON=python3.10 ./build-release.sh 0.1.0 +``` + +Outputs: + +```text +dist/blueorb_surface_python-0.1.0-py3-none-any.whl +dist/blueorb_surface_python-0.1.0.tar.gz +dist/blueorb-surface-python-0.1.0.sha256 +``` + +## 2. Build `spark-command-client` + +The version comes from `spark_command_client/pyproject.toml` and must be bumped +before a new release. + +```sh +cd /workspaces/spark/src/client/spark_command_client +PYTHON=python3.10 ./build-release.sh 0.1.0 +``` + +Outputs are written to that component's `dist/` directory with a checksum file. + +## 3. Build `spark-public-websocket` + +```sh +cd /workspaces/spark/src/client/spark_public_websocket +PYTHON=python3.10 ./build-release.sh 0.1.0 +``` + +The wheel declares compatible `blueorb-surface-python` and +`spark-command-client` ranges. A deployment must still pin exact wheel versions +in its release manifest. The same `dist/` directory contains a versioned +`spark-public-websocket-deploy-0.1.0.tar.gz` with its service and environment +templates. + +## 4. Build the self-contained BlueOrb RSS artifact + +The RSS version is passed to the .NET assembly metadata and artifact name: + +```sh +cd /home/bts/blueorb/RemoteStreamServer +./build-release.sh 0.1.0 linux-x64 +``` + +Outputs: + +```text +dist/blueorb-rss-0.1.0-linux-x64.tar.gz +dist/blueorb-rss-0.1.0-linux-x64.tar.gz.sha256 +``` + +The extracted directory contains `RemoteStreamServer` and all managed/native +runtime files required to start it without an installed .NET runtime. + +## 5. Build the self-contained Spark command bridge artifact + +The bridge must use the same released Spark SDK family as the target `sparkd`. +`SPARK_NUGET_SOURCE` can be a package-feed URL or a directory containing the +four released BTS NuGet packages. + +```sh +cd /workspaces/spark/src/client/spark_command_bridge + +SPARK_NUGET_SOURCE=/home/bts/blueorb/third_party/nuget \ +./build-release.sh \ + 0.1.0 \ + 3.2.3-defi-2-gefcbb26de1 \ + linux-x64 +``` + +Outputs: + +```text +dist/spark-command-bridge-0.1.0-linux-x64.tar.gz +dist/spark-command-bridge-0.1.0-linux-x64.tar.gz.sha256 +``` + +## Verify and publish artifacts + +Verify every archive before publishing it: + +```sh +sha256sum -c artifact-name.sha256 +``` + +Publish Python distributions to the team's package index. Publish .NET tarballs +and checksum files to the binary-release store. Keep immutable artifacts for +every deployed version; never replace an existing version in place. + +Before publication, install the three wheels together in a clean Python 3.10 +environment and run the package tests. Extract each .NET archive on a clean +compatible Linux host and start it with non-production configuration. + +## Deploy the Spark command bridge independently + +The existing `sparkd` deployment must expose a configuration-server address +reachable by the bridge. Addresses returned by that configuration service must +also be reachable from the bridge host. + +Create the service identity and directories once: + +```sh +sudo useradd --system --home /var/lib/spark-command-bridge \ + --shell /usr/sbin/nologin sparkbridge +sudo mkdir -p /opt/spark-command-bridge/releases /etc/spark-command-bridge +``` + +Install a version: + +```sh +sudo tar -xzf spark-command-bridge-0.1.0-linux-x64.tar.gz \ + -C /opt/spark-command-bridge/releases +sudo ln -sfn \ + /opt/spark-command-bridge/releases/spark-command-bridge-0.1.0-linux-x64 \ + /opt/spark-command-bridge/current +sudo chown -R sparkbridge:sparkbridge /opt/spark-command-bridge +``` + +Install configuration and the unit template: + +```sh +sudo cp /opt/spark-command-bridge/current/deploy/spark-command-bridge.env.example \ + /etc/spark-command-bridge/spark-command-bridge.env +sudo chmod 600 /etc/spark-command-bridge/spark-command-bridge.env +sudo cp /opt/spark-command-bridge/current/deploy/spark-command-bridge.service \ + /etc/systemd/system/ +``` + +Edit the environment file with the real configuration-server URL and +credentials, then start the service: + +```sh +sudo systemctl daemon-reload +sudo systemctl enable --now spark-command-bridge +sudo systemctl status spark-command-bridge +journalctl -u spark-command-bridge -f +``` + +Only port `50051` needs to be reachable by the WebSocket service. It should not +be exposed publicly. + +## Deploy BlueOrb RSS independently + +```sh +sudo useradd --system --home /var/lib/blueorb-rss \ + --shell /usr/sbin/nologin blueorb +sudo mkdir -p /opt/blueorb-rss/releases /etc/blueorb-rss + +sudo tar -xzf blueorb-rss-0.1.0-linux-x64.tar.gz \ + -C /opt/blueorb-rss/releases +sudo ln -sfn \ + /opt/blueorb-rss/releases/blueorb-rss-0.1.0-linux-x64 \ + /opt/blueorb-rss/current +sudo chown -R blueorb:blueorb /opt/blueorb-rss + +sudo cp /home/bts/blueorb/blueorb.config.example.json \ + /etc/blueorb-rss/blueorb.config.json +sudo cp /opt/blueorb-rss/current/deploy/blueorb-rss.env.example \ + /etc/blueorb-rss/blueorb-rss.env +sudo cp /opt/blueorb-rss/current/deploy/blueorb-rss.service \ + /etc/systemd/system/ + +sudo systemctl daemon-reload +sudo systemctl enable --now blueorb-rss +sudo systemctl status blueorb-rss +journalctl -u blueorb-rss -f +``` + +Edit `/etc/blueorb-rss/blueorb.config.json` for the target environment before +starting RSS. Port `5085` should be reachable by the WebSocket service, but not +published to untrusted networks. + +## Deploy the public WebSocket independently + +Place the exact three approved wheels on the host or download them from the +package index. Create one immutable virtual environment per gateway release: + +```sh +sudo useradd --system --home /var/lib/spark-public-websocket \ + --shell /usr/sbin/nologin sparkwebsocket +sudo mkdir -p /opt/spark-public-websocket/releases /etc/spark-public-websocket + +sudo python3.10 -m venv /opt/spark-public-websocket/releases/0.1.0 +sudo /opt/spark-public-websocket/releases/0.1.0/bin/python -m pip install \ + ./blueorb_surface_python-0.1.0-py3-none-any.whl \ + ./spark_command_client-0.1.0-py3-none-any.whl \ + ./spark_public_websocket-0.1.0-py3-none-any.whl + +sudo ln -sfn /opt/spark-public-websocket/releases/0.1.0 \ + /opt/spark-public-websocket/current +sudo chown -R sparkwebsocket:sparkwebsocket /opt/spark-public-websocket + +tar -xzf spark-public-websocket-deploy-0.1.0.tar.gz +sudo cp deploy/spark-public-websocket.env.example \ + /etc/spark-public-websocket/spark-public-websocket.env +sudo cp deploy/spark-public-websocket.service /etc/systemd/system/ + +sudo systemctl daemon-reload +sudo systemctl enable --now spark-public-websocket +sudo systemctl status spark-public-websocket +journalctl -u spark-public-websocket -f +``` + +Set `BLUEORB_ADDRESS` and `SPARK_COMMAND_ADDRESS` to the independently deployed +backend addresses. Port `8090` is the only new public listener. + +## Smoke test the deployed path + +Run the existing client from any machine allowed to reach the WebSocket: + +```sh +python examples/stream_docs.py --url ws://websocket-host:8090/v1/ws +``` + +Then exercise `enter_order`, `update_order`, `delete_order`, and +`create_synthetic_spread` using non-production Spark identifiers. The release is +not functionally complete until all four commands traverse the WebSocket, +bridge, Quickbus, and real `sparkd`. + +## Upgrade and rollback + +Never overwrite `/opt//current`. Extract or create the new version +under `releases/`, atomically repoint `current`, and restart only that service. +Rollback uses the same operation with the previous release directory. + +Python library releases do not restart RSS or the bridge. Backend releases do +not require rebuilding the gateway unless their public contract compatibility +changes. + +## Still required before production exposure + +- Real `sparkd` end-to-end and failure-path verification. +- A decision on durable versus process-local order idempotency. +- Authentication, authorization, TLS, secret management, and rate limiting. +- Health monitoring, correlation IDs, structured timings, and alerts. +- Independent restart, outage, rollback, load, and latency tests. diff --git a/src/client/spark_public_websocket/.gitignore b/src/client/spark_public_websocket/.gitignore new file mode 100644 index 000000000..c50bcdc95 --- /dev/null +++ b/src/client/spark_public_websocket/.gitignore @@ -0,0 +1,3 @@ +build/ +dist/ +src/*.egg-info/ diff --git a/src/client/spark_public_websocket/PROTOCOL.md b/src/client/spark_public_websocket/PROTOCOL.md new file mode 100644 index 000000000..768146c40 --- /dev/null +++ b/src/client/spark_public_websocket/PROTOCOL.md @@ -0,0 +1,137 @@ +# WebSocket protocol v1 + +Connect to `/v1/ws`. A library host may inject an authentication provider that +validates the handshake before acceptance. The bundled development executable +currently uses an anonymous principal. Every client request is one JSON text +message with a unique string or integer `id`: + +```json +{"jsonrpc":"2.0","id":"req-1","method":"ping","params":{}} +``` + +Successful responses retain that ID: + +```json +{"jsonrpc":"2.0","id":"req-1","result":{"pong":true}} +``` + +Failures have an error code and message: + +```json +{"jsonrpc":"2.0","id":"req-1","error":{"code":-32602,"message":"invalid fields: quantity","data":{"code":"invalid_params"}}} +``` + +Requests larger than 64 KiB are rejected. An individual connection may have at most 32 active subscriptions. Send one JSON object per WebSocket text frame. Binary frames close the connection with code 1003. + +## BlueOrb subscriptions + +The `subscription` method forwards unrestricted DSL through the independently +packaged BlueOrb Python client to RemoteStreamServer: + +```json +{"jsonrpc":"2.0","id":"blueorb-1","method":"subscription","params":{"subscription_id":"query-1","dsl":"phoenix_bbo(\"SOL\")"}} +``` + +The acknowledgement is queued before the first packet: + +```json +{"jsonrpc":"2.0","id":"blueorb-1","result":{"subscription_id":"query-1"}} +``` + +Packets use the same `subscription` method name but, as server notifications, +have no request `id`: + +```json +{"jsonrpc":"2.0","method":"subscription","params":{"subscription_id":"query-1","packet":{"table":"phoenix_bbo","schema":{"name":"phoenix_bbo","columns":[]},"current":[],"added":[],"removed":[],"kind":"snapshot","sequence":1}}} +``` + +Packet kinds are `snapshot` and `delta`. Rows are objects keyed by schema column +name. Decimal values are JSON strings, datetimes are ISO-8601 strings, and other +values retain their JSON boolean, integer, floating-point, string, or null type. +The packet contains BlueOrb's reconstructed `current` table plus the `added` and +`removed` changes. + +`unsubscribe` and `unsubscribe_all` affect BlueOrb subscriptions on the current +connection. Messages already queued before an unsubscribe acknowledgement may +still be delivered; the client should ignore them by subscription ID. + +This handoff intentionally allows any DSL accepted by RemoteStreamServer. The +development server uses an anonymous identity and does not apply operator, +instrument, filesystem, or configuration restrictions. It must therefore be +treated as a trusted-development interface until security is added. + +## Orders + +Price and quantity **must** be positive, finite decimal strings; JSON numbers are rejected to avoid floating-point rounding. A limit order requires a price; a market order must omit price. `client_order_id` is required for idempotent submission. The authenticated principal, rather than a user field in the request, determines who is submitting. + +```json +{"jsonrpc":"2.0","id":"req-4","method":"enter_order","params":{"client_order_id":"strategy-a-0001","account":"ACC A","exchange":"okx","exchange_security_name":"SOL-USDC","side":"buy","order_type":"limit","quantity":"2","price":"100.25"}} +``` + +The response means the command was accepted by Spark, **not** that the order was +filled or accepted by an exchange. Order/fill streaming is outside this release: + +```json +{"jsonrpc":"2.0","id":"req-4","result":{"order_id":"456","status":"accepted","message":null}} +``` + +Update quantity and/or price: + +```json +{"jsonrpc":"2.0","id":"req-5","method":"update_order","params":{"order_id":"456","quantity":"3","price":"100.50"}} +``` + +Request cancellation (the method name follows the existing API vocabulary; order history is not deleted): + +```json +{"jsonrpc":"2.0","id":"req-6","method":"delete_order","params":{"order_id":"456"}} +``` + +For either operation, the result has the same `order_id`, `status`, and optional `message` fields as `enter_order`. Unsupported order types, venues, or modifications must produce an error rather than silently changing meaning. + +If a submission times out after reaching the SDK, its outcome may be unknown. The SDK must return `outcome_unknown` and the client must query/reconcile using `client_order_id` before retrying. Do not blindly submit a second order. + +## Create a synthetic spread + +`create_synthetic_spread` defines a two-leg synthetic security. It is the public v1 counterpart of the C# WebSocket server's `CREATE_SYNTHETIC_SPREAD` operation. Each leg can be identified either by `security_id` or by an `exchange` and `exchange_security_name` pair. A leg must use exactly one locator form. Named string enum values are used instead of internal protobuf numbers. + +Only the two leg locators are required. Omitted fields are resolved by the SDK/backend from its configured synthetic-spread preset and security metadata; the gateway does not choose defaults. + +```json +{"jsonrpc":"2.0","id":"req-7","method":"create_synthetic_spread","params":{"leg1_security_id":"123","leg2_security_id":"456","name":"calendar-spread","tick_size":"0.01","leg1_quantity":"1","leg1_side":"buy","leg2_quantity":"1","leg2_price_multiplier":"-1","leg2_side":"sell","spreader_type":"requote"}} +``` + +The exchange/name form is compatible with the original C# WebSocket request: + +```json +{"jsonrpc":"2.0","id":"req-8","method":"create_synthetic_spread","params":{"leg1_exchange":"okx","leg1_exchange_security_name":"SOL-USDC","leg2_exchange":"orca","leg2_exchange_security_name":"SOL-USDC-1"}} +``` + +A successful response returns the public ID assigned to the synthetic security: + +```json +{"jsonrpc":"2.0","id":"req-7","result":{"security_id":"789"}} +``` + +Optional contract fields are `name`, `symbol`, `currency`, `tick_size`, `cash_per_point`, `price_multiplier`, `main_fraction`, `sub_fraction`, `price_display_format`, and `price_calc`. Strategy fields are `cancel_hedges_on_cancel`, `hedge_pricing`, `spreader_type`, and `lean_quantity_ratio`. Each leg accepts fields prefixed with `leg1_` or `leg2_`: `quantity`, `price_multiplier`, `leg_delta`, `side`, `is_active_quoting`, `enable_hedging`, and `market_data_type`. + +Decimal fields follow the same precision rule as orders: they must be finite JSON strings. Quantities, tick size, cash per point, the contract price multiplier, and lean quantity ratio must be positive. Leg price multipliers may be negative but cannot be zero. + +Valid named values are: + +| Field | Values | +| --- | --- | +| `price_calc` | `standard`, `net_change`, `notional_leg` | +| `hedge_pricing` | `cached_drivers`, `recalculate_crosses` | +| `spreader_type` | `requote`, `reverse_hedge`, `sniper` | +| `leg1_side`, `leg2_side` | `buy`, `sell` | +| `leg1_market_data_type`, `leg2_market_data_type` | `merged`, `direct` | + +The gateway forwards this call through `spark-command-client`; the standalone +bridge creates the Spark synthetic security and updates its execution strategy. + +## Error codes and lifecycle + +The numeric `error.code` follows JSON-RPC 2.0: `-32700` for `invalid_json`, `-32600` for `invalid_request`, `-32601` for `method_not_found`, `-32602` for `invalid_params`, `-32603` for `internal_error`, and `-32000` for application/server errors. The stable symbolic code is `error.data.code`. The gateway generates `duplicate_subscription`, `unknown_subscription`, `subscription_limit`, and `request_too_large` as application errors. The SDK may additionally return `not_found`, `backend_unavailable`, `rejected`, or `outcome_unknown`. An unexpected exception is logged server-side and exposed only as `internal_error`. + +Authentication failures close the handshake with policy-violation code 1008. If the outgoing queue fills, the connection closes with code 1013; clients must reconnect and rebuild their subscriptions. The gateway makes no durable-delivery guarantee for WebSocket events. diff --git a/src/client/spark_public_websocket/README.md b/src/client/spark_public_websocket/README.md new file mode 100644 index 000000000..135d0df52 --- /dev/null +++ b/src/client/spark_public_websocket/README.md @@ -0,0 +1,211 @@ +# Spark and BlueOrb public WebSocket API + +This directory is a standalone Python package that a WebSocket/API team can +develop without checking out or loading `sparkd`. It combines two independently +owned backend surfaces behind `/v1/ws`: + +- Spark commands use the separately packaged `spark-command-client`. +- BlueOrb DSL subscriptions use the required, separately published + `blueorb-surface-python` package. + +The gateway never imports `libspark`, Quickbus, Spark protobufs, or BlueOrb's C# +assemblies. The full JSON-RPC contract is in [PROTOCOL.md](PROTOCOL.md). +The deployed four-service architecture, exposed layers, implementation status, +and remaining production work are tracked in +[SYSTEM_ARCHITECTURE_AND_STATUS.md](SYSTEM_ARCHITECTURE_AND_STATUS.md). +Versioned artifact creation and independent component deployment are documented +in [../RELEASE_AND_DEPLOYMENT.md](../RELEASE_AND_DEPLOYMENT.md). + +## Team and package boundaries + +| Owner | Responsibility | Artifact consumed by the gateway | +| --- | --- | --- | +| Spark team | `sparkd`, bridge, and generated Python client | `spark-command-client` | +| BlueOrb team | DSL engine, RemoteStreamServer, Python surface | `blueorb-surface-python` | +| WebSocket team | Public JSON contract, lifecycle, adapters, and server | `spark-public-websocket` | + +`PublicSparkSdk`, `PublicBlueOrb`, and `WebSocketAuthenticator` remain narrow +dependency-injection contracts. Tests use fakes, so gateway work does not need +either backend running. + +## Install and run + +Python 3.10 or newer is required. For a source checkout with locally built +packages: + +```sh +python -m pip install /path/to/blueorb_surface_python-0.1.0-py3-none-any.whl +python -m pip install /path/to/spark_command_client-0.1.0-py3-none-any.whl +python -m pip install /path/to/spark_public_websocket-0.1.0-py3-none-any.whl +spark-public-websocket \ + --blueorb-address http://localhost:5085 \ + --spark-command-address 127.0.0.1:50051 +``` + +For editable development from the current checkouts: + +```sh +python -m pip install -e /home/bts/blueorb/BlueOrb.Surface.Python +python -m pip install -e /workspaces/spark/src/client/spark_command_client +python -m pip install -e '/workspaces/spark/src/client/spark_public_websocket[client,test]' +spark-public-websocket \ + --blueorb-address http://localhost:5085 \ + --spark-command-address 127.0.0.1:50051 +``` + +The default listener is `127.0.0.1:8090`. Port 8090 avoids Spark's default +configuration service on port 8000. Configuration can be supplied through +arguments or environment variables: + +```sh +PUBLIC_WS_HOST=127.0.0.1 \ +PUBLIC_WS_PORT=8090 \ +BLUEORB_ADDRESS=http://localhost:5085 \ +SPARK_COMMAND_ADDRESS=127.0.0.1:50051 \ +spark-public-websocket +``` + +With RSS and the gateway running, request BlueOrb's stream documentation through +the public WebSocket and print the acknowledgement, first packet, and +unsubscribe response: + +```sh +python examples/stream_docs.py +``` + +Use `--url ws://host:port/v1/ws` when the gateway is not on the default local +address. + +The executable can run with either backend disabled for isolated development: + +```sh +spark-public-websocket --without-blueorb +spark-public-websocket --without-spark +``` + +Normal installations require both client wheels and fail fast if one is +missing. The `--without-*` switches are for isolated protocol development. + +## Connecting the independently packaged Spark client + +The default runtime constructs `spark-command-client` from +`SPARK_COMMAND_ADDRESS`. A different implementation can still be injected for +tests or specialized environments: + +```python +# package: company_spark_sdk +def create_sdk(): + return SparkSdk(...) +``` + +Load it without modifying this gateway: + +```sh +spark-public-websocket --spark-sdk-factory company_spark_sdk:create_sdk +``` + +The same value can be set with `SPARK_SDK_FACTORY`. Applications needing their +own authentication provider can compose the library directly: + +```python +from blueorb import BlueOrbStreamHost +from spark_public_websocket import BlueOrbAdapter, create_app + +app = create_app( + sdk=my_spark_sdk, + authenticator=my_authenticator, + blueorb=BlueOrbAdapter(BlueOrbStreamHost("http://localhost:5085")), +) +``` + +## Public methods + +| Method | Backend | Purpose | +| --- | --- | --- | +| `subscription` | BlueOrb | Execute unrestricted BlueOrb DSL and stream packets | +| `unsubscribe` | Local | Stop a BlueOrb subscription | +| `unsubscribe_all` | Local | Stop all subscriptions on the connection | +| `enter_order` | Spark SDK | Submit a market or limit order | +| `update_order` | Spark SDK | Change an order | +| `delete_order` | Spark SDK | Request cancellation | +| `create_synthetic_spread` | Spark SDK | Define a two-leg synthetic spread | +| `ping` | Local | Check the WebSocket request loop | + +BlueOrb requests and packet notifications both use `subscription`; request +messages have an `id`, while server notifications do not. Spark commands are +unary request/response operations and have no public Spark subscription method. + +The updated runtime inventory is documented in +[STREAM_CATALOG.md](STREAM_CATALOG.md). BlueOrb DSL is intentionally unrestricted +in this development handoff, so any operator registered by RemoteStreamServer +can be requested. This includes operators with configuration, file, network, or +other side effects. Keep this version on a trusted development network. + +## Runtime behavior + +The BlueOrb package exposes a blocking callback API. `BlueOrbAdapter` runs that +call in a worker thread, transfers packets safely onto the asyncio loop, and +cancels its gRPC call when the WebSocket subscription ends. Both the adapter and +the connection use bounded queues so a slow client cannot block a backend +callback indefinitely. + +The development executable uses an anonymous principal because authentication +is currently out of scope. `create_app()` still accepts an authenticator so a +client team can add credentials later without changing the public request +contract. + +The gateway caps inbound JSON at 64 KiB, active subscriptions at 32 per +connection, and the outgoing queue at 256 messages. Queue overflow closes a +slow connection with code 1013. + +## Tests and builds + +```sh +python -m pytest tests +python -m build +``` + +Contract tests use fake Spark and BlueOrb implementations. Package integration +tests carry an order through the actual generated Spark gRPC client and carry a +BlueOrb packet through the actual +`blueorb-surface-python` `BlueOrbStreamHost`, and carries a packet through +`/v1/ws`. It validates the complete Python path without requiring the .NET +RemoteStreamServer or `sparkd`. + +## Deployed system + +```mermaid +flowchart LR + Client["Client
PUBLIC"] + + subgraph PublicLayer["PUBLIC API LAYER"] + Gateway["spark-public-websocket 0.1.3
:8090/v1/ws
JSON-RPC methods and subscription events"] + end + + subgraph PackageLayer["IN-PROCESS PACKAGE LAYER"] + BlueOrbPackage["blueorb-surface-python 0.1.0"] + SparkPackage["spark-command-client 0.1.2"] + end + + subgraph InternalLayer["INTERNAL SERVICE LAYER"] + RSS["blueorb-rss 0.1.2-spark4614b60
streaming gRPC :5085
BlueOrb DSL surface"] + Bridge["spark-command-bridge 0.1.3-spark4614b60
unary gRPC :50051
four commands + Health"] + end + + subgraph SparkLayer["SPARK BACKEND LAYER"] + Sparkd["sparkd 3.2.3+4614b60
configuration :8000 + Quickbus
not a public WebSocket surface"] + end + + Client -->|"public WebSocket"| Gateway + Gateway --> BlueOrbPackage + Gateway --> SparkPackage + BlueOrbPackage -->|"internal gRPC"| RSS + SparkPackage -->|"internal gRPC"| Bridge + RSS -.->|"Spark-backed streams"| Sparkd + Bridge -->|"Spark SDK / Quickbus"| Sparkd +``` + +Only port 8090 is intended for client access. Ports 5085 and 50051 are backend +service APIs, while port 8000 and Quickbus belong to the Spark deployment. See +[SYSTEM_ARCHITECTURE_AND_STATUS.md](SYSTEM_ARCHITECTURE_AND_STATUS.md) for the +method-level exposure table, verified behavior, versions, and remaining work. diff --git a/src/client/spark_public_websocket/STREAM_CATALOG.md b/src/client/spark_public_websocket/STREAM_CATALOG.md new file mode 100644 index 000000000..437f9b8ee --- /dev/null +++ b/src/client/spark_public_websocket/STREAM_CATALOG.md @@ -0,0 +1,135 @@ +# DSL stream catalog + +This catalog records the 77 stream names in the supplied stream inventory. They are DSL/runtime stream definitions, not additional WebSocket methods. The inventory includes data sources, transforms, and sinks. A host SDK may support these, but the current public `/v1/ws` gateway only validates the six `subscribe.type` values in [PROTOCOL.md](PROTOCOL.md); it does **not** yet accept a DSL expression or any of the names below as `subscribe.type`. Exposing them publicly requires a separate, reviewed request contract and permission rules, especially for file, remote-compute, configuration, and publishing streams. + +Names and descriptions below are copied or lightly edited from the provided catalog; examples are DSL expressions, not WebSocket JSON payloads. The catalog lists capabilities, not a guarantee that every provider is configured or available in each deployment. + +## Business.Analytics + +| DSL name | Class | Role | Description | +| --- | --- | --- | --- | +| `adx` | `ADXStream` | Transform | Calculates average directional index values over OHLC input rows. | +| `arbitrage_pair_opportunities` | `ArbitragePairOpportunityStream` | Transform | Evaluates arbitrage pair opportunities from configured pair definitions. | +| `arbitrage_pairs` | `ArbitragePairStream` | Source | Emits configured arbitrage pair definitions. | +| `atr` | `ATRStream` | Transform | Calculates average true range over OHLC input rows. | +| `ema` | `EMAStream` | Transform | Calculates an exponential moving average over an input price column. | +| `macd` | `MACDStream` | Transform | Calculates MACD, signal, and histogram values over an input price series. | +| `macd_ui` | `MACDUIStream` | Transform | Builds a UI-friendly MACD stream from an input price series. | +| `parabolic_sar` | `ParabolicSARStream` | Transform | Calculates parabolic SAR values over OHLC input rows. | +| `rsi` | `RSIStream` | Transform | Calculates relative strength index values over an input price series. | +| `rsi_ui` | `RSIUIStream` | Transform | Builds a UI-friendly RSI stream from an input price series. | +| `stochastic` | `StochasticOscillatorStream` | Transform | Calculates stochastic oscillator values over OHLC input rows. | +| `volume_profile` | `VolumeProfileStream` | Transform | Builds a volume profile from input price and volume rows. | +| `vwap` | `VWAPStream` | Transform | Calculates volume-weighted average price over an input price and volume series. | +| `wilder_ma` | `WilderMovingAverageStream` | Transform | Calculates Wilder's moving average over an input value column. | + +## Business.Bars + +| DSL name | Class | Role | Description | +| --- | --- | --- | --- | +| `bar_builder` | `BarBuilderStream` | Transform | Builds OHLCV bars from an input trade stream. | +| `heikin_ashi` | `HeikinAshiStream` | Transform | Transforms OHLC bars into Heikin-Ashi bars. | + +## Business.MarketData + +| DSL name | Class | Role | Description | +| --- | --- | --- | --- | +| `bison_markets` | `BisonMarketsStream` | Source | Fetches Bison market metadata for markets matching a status filter. | +| `databento_bbo` | `DatabentoBBOStream` | Source | Streams live Databento best bid and offer for an instrument. | +| `databento_book` | `DatabentoBookStream` | Source | Streams live Databento order-book depth for an instrument. | +| `databento_instrument_definition` | `DatabentoInstrumentDefinitionStream` | Source | Streams Databento instrument definition snapshots for an instrument. | +| `databento_market_data` | `DatabentoMarketDataStream` | Source | Streams live Databento market data for a symbol and schema. | +| `databento_replay_trade` | `DatabentoReplayTradeStream` | Source | Replays Databento trade data from a local file. | +| `databento_statistics` | `DatabentoStatisticsStream` | Source | Streams latest Databento venue statistics for an instrument. | +| `databento_trades` | `DatabentoTradesStream` | Source | Streams live Databento trades for an instrument. | +| `defillama_dex_volumes` | `DeFiLlamaDexVolumesStream` | Source | Fetches DeFiLlama DEX volume data. | +| `geckoterminal_trending_pools` | `GeckoTerminalTrendingPoolsStream` | Source | Fetches GeckoTerminal trending pool data. | +| `hyperliquid_bbo` | `HyperliquidBBOStream` | Source | Streams Hyperliquid best bid and offer for an instrument. | +| `hyperliquid_book` | `HyperliquidBookStream` | Source | Streams Hyperliquid order-book depth for an instrument. | +| `hyperliquid_instrument_definition` | `HyperliquidInstrumentDefinitionStream` | Source | Fetches Hyperliquid instrument definition data. | +| `hyperliquid_market_data` | `HyperliquidMarketDataStream` | Source | Routes a Hyperliquid market-data request to the appropriate Hyperliquid stream. | +| `hyperliquid_trades` | `HyperliquidTradesStream` | Source | Streams Hyperliquid trades for an instrument. | +| `instrument_list` | `InstrumentListStream` | Source | Combines supported instrument definition streams into a normalized instrument list. | +| `live_market_data` | `LiveMarketDataStream` | Source | Routes a live venue market-data request to the configured provider stream. | +| `market_data` | `MarketDataStream` | Source | Routes a provider-neutral market-data request to the configured concrete provider stream. | +| `phoenix_bbo` | `PhoenixBBOStream` | Source | Streams Phoenix best bid and offer for a perp instrument. | +| `phoenix_book` | `PhoenixBookStream` | Source | Streams Phoenix order-book depth for a perp instrument. | +| `phoenix_funding_rate` | `PhoenixFundingRateStream` | Source | Streams Phoenix funding-rate updates for a perp instrument. | +| `phoenix_instrument_definition` | `PhoenixInstrumentDefinitionStream` | Source | Fetches Phoenix instrument definition and exchange market configuration. | +| `phoenix_trades` | `PhoenixTradesStream` | Source | Polls Phoenix recent trades for a perp instrument. | +| `replay_market_data` | `ReplayMarketDataStream` | Source | Replays historical market-data rows from a stored dataset. | +| `replay_trade` | `ReplayTradeStream` | Source | Replays trade rows from a local trade data file. | +| `spark_bbo` | `SparkBBOStream` | Source | Streams Spark best bid and offer for an instrument. | +| `spark_book` | `SparkBookStream` | Source | Streams Spark order-book depth for an instrument. | +| `spark_instrument_definition` | `SparkInstrumentDefinitionStream` | Source | Fetches Spark instrument definition data. | +| `spark_instrument_list` | `InstrumentListStream` | Source | Combines supported instrument definition streams into a normalized instrument list. | +| `spark_instruments` | `SparkInstrumentStream` | Source | Fetches Spark instruments as a market-data source. | +| `spark_orders` | `SparkOrderStream` | Source | Streams Spark order events for an instrument. | +| `spark_trades` | `SparkTradesStream` | Source | Streams Spark trades for an instrument. | + +## Business.Risk + +| DSL name | Class | Role | Description | +| --- | --- | --- | --- | +| `margin_requirement` | `MarginRequirementStream` | Transform | Estimates from-flat margin requirements for a proposed trade using venue margin data. | +| `phoenix_margin` | `PhoenixMarginStream` | Source | Fetches Phoenix public margin, risk, and leverage-tier configuration for a perp instrument. | + +## Config + +| DSL name | Class | Role | Description | +| --- | --- | --- | --- | +| `config` | `ConfigStream` | Source | Emits the effective application configuration as rows of section, key, and value data. | + +## CoreOperators + +| DSL name | Class | Role | Description | +| --- | --- | --- | --- | +| `append` | `AppendStream` | Transform | Appends rows from multiple streams with union-all semantics. | +| `cartesian_product` | `CartesianProductStream` | Transform | Produces every left/right row combination from two input streams. | +| `count` | `CountStream` | Transform | Emits a one-row table containing the current row count of an input stream. | +| `csv_reader` | `CSVReaderStream` | Source | Reads a CSV file into a stream table. | +| `csv_writer` | `CSVWriterStream` | Sink | Writes stream rows to a CSV file. | +| `filter` | `FilterStream` | Transform | Filters rows from an input stream using a row predicate. | +| `group_by` | `GroupByStream` | Transform | Groups rows by one or more columns and applies aggregate reductions. | +| `join` | `JoinStream` | Transform | Performs a left outer join between two input streams. | +| `literal` | `LiteralStream` | Source | Creates a static stream table from literal rows. | +| `map` | `MapStream` | Transform | Adds or replaces columns by evaluating row-wise expressions. | +| `multi_row_rolling_math` | `MultiRowRollingMathStream` | Transform | Calculates rolling math values over multiple rows in an input stream. | +| `name_converter` | `NameConverterStream` | Transform | Converts stream table and column names using the configured naming conversion. | +| `project` | `ProjectStream` | Transform | Selects, hides, or renames columns without computing new values. | +| `rolling_math` | `MultiRowRollingMathStream` | Transform | Calculates rolling math values over multiple rows in an input stream. | +| `sort` | `SortStream` | Transform | Orders all current rows from an input stream by one or more columns. | +| `spread_bbo` | `SpreadBBOStream` | Transform | Combines two BBO streams into a spread BBO view. | +| `stream_docs` | `StreamDocumentationStream` | Source | Emits documentation metadata for streams registered in the active DSL catalog. | +| `time_based_rolling_filter` | `TimeBasedRollingFilterStream` | Transform | Keeps rows whose timestamps fall within a rolling time window. | +| `time_event` | `TimeEventStream` | Source | Emits a time event row on a scheduler-driven interval. | +| `time_series` | `TimeSeriesStream` | Transform | Retains incoming rows as a historical time series, optionally with a maximum row count. | +| `top` | `TopStream` | Transform | Selects the first N rows from an input stream, optionally after sorting. | + +## Remote + +| DSL name | Class | Role | Description | +| --- | --- | --- | --- | +| `publisher` | `PublisherStream` | Sink | Publishes an input stream to a remote named table through the table broker. | +| `remote` | `RemoteComputeStream` | Source | Subscribes to a remote server-side DSL computation and streams its packets locally. | +| `remote_table` | `RemoteTableStream` | Source | Subscribes to a named remote table through the table broker. | +| `rfs_pub_state` | `RFSPubStateStream` | Source | Subscribes to the remote table broker publication-state table. | +| `rfs_remote_compute_state` | `RFSRemoteComputeStateStream` | Source | Subscribes to the remote compute server state table. | + +## Example DSL expressions + +These examples come from the supplied inventory. Send an expression as the +`dsl` field of a `/v1/ws` BlueOrb `subscription` request. Whether an expression +can execute depends on the operators registered by the connected +RemoteStreamServer. + +```text +hyperliquid_bbo("SOL") +phoenix_book("SOL") +market_data("perp", "SOL", "PHOENIX", "margin") +margin_requirement("perp", "SOL", "PHOENIX", "margin", 145.25, 10.0) +instrument_list() +remote_table("rfs_pub_stats") +``` + +The inventory also includes two DSL aliases for the same `InstrumentListStream` class (`instrument_list` and `spark_instrument_list`) and two for `MultiRowRollingMathStream` (`multi_row_rolling_math` and `rolling_math`). Both names are listed above as provided. diff --git a/src/client/spark_public_websocket/SYSTEM_ARCHITECTURE_AND_STATUS.md b/src/client/spark_public_websocket/SYSTEM_ARCHITECTURE_AND_STATUS.md new file mode 100644 index 000000000..f993c648e --- /dev/null +++ b/src/client/spark_public_websocket/SYSTEM_ARCHITECTURE_AND_STATUS.md @@ -0,0 +1,177 @@ +# Spark and BlueOrb WebSocket system architecture and status + +Last updated: 2026-09-30 + +This document describes the system that is implemented and deployed. + +## Deployed system + +The deployment consists of four independently operated services: + +1. `spark-public-websocket` +2. `blueorb-rss` +3. `spark-command-bridge` +4. `sparkd` + +The WebSocket service is the client-facing API. BlueOrb RSS owns DSL execution +and streaming. The command bridge owns the translation from the stable command +contract to the Spark SDK. `sparkd` remains independently built and deployed by +the existing Spark scripts. + +```mermaid +flowchart LR + User["Client application or browser"] + + subgraph Public["PUBLIC API LAYER"] + WS["spark-public-websocket 0.1.3
0.0.0.0:8090 /v1/ws
JSON-RPC over WebSocket

EXPOSED METHODS
subscription / unsubscribe / unsubscribe_all
enter_order / update_order / delete_order
create_synthetic_spread / ping"] + end + + subgraph Packages["PYTHON PACKAGE LAYER — in the WebSocket process"] + BOClient["blueorb-surface-python 0.1.0
BlueOrb client API; not a network listener"] + CommandClient["spark-command-client 0.1.2
generated async gRPC client; not a network listener"] + end + + subgraph Internal["INTERNAL SERVICE LAYER — do not expose publicly"] + RSS["blueorb-rss 0.1.2-spark4614b60
0.0.0.0:5085
HTTP/2 streaming gRPC

EXPOSED TO GATEWAY
RemoteStreamsTransport / TableBroker
registered BlueOrb DSL operators"] + Bridge["spark-command-bridge 0.1.3-spark4614b60
0.0.0.0:50051
unary gRPC

EXPOSED TO GATEWAY
EnterOrder / UpdateOrder / DeleteOrder
CreateSyntheticSpread / Health"] + end + + subgraph Spark["SPARK LAYER"] + Sparkd["sparkd 3.2.3+4614b60
configuration service: :8000
Quickbus and Spark services

NOT A PUBLIC WEBSOCKET CONTRACT"] + end + + User -->|"public ws://host:8090/v1/ws"| WS + WS -->|"in-process subscription adapter"| BOClient + WS -->|"in-process command adapter"| CommandClient + BOClient -->|"internal streaming gRPC :5085"| RSS + CommandClient -->|"internal unary gRPC :50051"| Bridge + RSS -.->|"Spark-backed BlueOrb sources"| Sparkd + Bridge -->|"Spark SDK / Quickbus"| Sparkd +``` + +### Exposure policy + +| Layer | Surface | Intended consumers | Exposure | +| --- | --- | --- | --- | +| Public API | WebSocket `/v1/ws` on port 8090 | Client applications | Public development endpoint | +| Public JSON-RPC | BlueOrb subscription methods, four Spark commands, and `ping` | WebSocket clients | Exposed through `/v1/ws` | +| Python packages | `blueorb-surface-python`, `spark-command-client` | WebSocket process and Python developers | Package APIs only; no listeners | +| BlueOrb service | Streaming gRPC on port 5085 | `blueorb-surface-python` | Internal service endpoint | +| Spark command service | Unary gRPC on port 50051 | `spark-command-client` | Internal service endpoint | +| Spark service | Configuration service on port 8000 and Quickbus endpoints | RSS, bridge, Spark tools | Backend/deployment endpoint, not part of the public WebSocket API | + +The services currently bind to `0.0.0.0`. Network firewall rules must enforce +the intended exposure: publish 8090 to clients and restrict 5085, 50051, and +Spark backend ports to trusted hosts or the service network. + +## Implemented request paths + +### BlueOrb streaming + +```text +WebSocket subscription request + -> gateway BlueOrb adapter + -> blueorb-surface-python + -> RSS streaming gRPC + -> BlueOrb DSL engine + -> snapshot/delta packets + -> WebSocket subscription notifications +``` + +The public method is `subscription`. DSL access is intentionally unrestricted +for this development deployment. `stream_docs()` and +`spark_instrument_definition()` have been verified end to end. A filtered +instrument-definition subscription successfully returns synthetic spreads. + +### Spark commands + +```text +WebSocket command request + -> gateway Spark adapter + -> spark-command-client + -> command-only gRPC contract + -> spark-command-bridge + -> compatible Bts.Spark.Sdk + -> Quickbus / sparkd + -> JSON-RPC result or error +``` + +Implemented commands are `enter_order`, `update_order`, `delete_order`, and +`create_synthetic_spread`. The bridge does not call RSS and the gateway does +not load native Spark libraries. + +Order entry accepts exactly one security locator: + +- `security_id`; or +- `exchange` and `exchange_security_name`. + +The named form matches the useful lookup behavior of the C# WebSocket. The +bridge resolves it case-insensitively from its live Spark security cache. +Synthetic-spread legs support the same two locator forms. + +## Component and artifact status + +| Component | Implemented artifact | Deployed version/status | +| --- | --- | --- | +| Public gateway | `spark-public-websocket` wheel | `0.1.3`, active on port 8090 | +| Spark Python client | `spark-command-client` wheel | `0.1.2`, installed in gateway release | +| BlueOrb Python client | `blueorb-surface-python` wheel | `0.1.0`, installed in gateway release | +| Spark command bridge | Self-contained Linux x64 release | `0.1.3-spark4614b60`, active on port 50051 | +| BlueOrb RSS | Self-contained Linux x64 release | `0.1.2-spark4614b60`, active on port 5085 | +| Spark daemon | Existing Spark deployment | `3.2.3+4614b60`, running separately | +| Command contract | `spark.command.v1` Protobuf | Generated C# server and Python client bindings | + +The bridge and RSS use Spark project artifacts from commit `4614b60`, matching +the deployed `sparkd`. This removes the prior `VENUE_PHOENIX` and configuration +schema incompatibilities. + +## Verified behavior + +| Capability | Status | Evidence | +| --- | --- | --- | +| Gateway startup and WebSocket listener | Working | `spark-public-websocket.service` active on 8090 | +| RSS startup and streaming endpoint | Working | `blueorb-rss.service` active on 5085 | +| Bridge startup and command endpoint | Working | `spark-command-bridge.service` active on 50051 | +| BlueOrb `stream_docs()` | Working | Acknowledgement, packet, and unsubscribe verified | +| Spark instrument definitions through BlueOrb | Working | Snapshot received through the public WebSocket | +| Synthetic-spread list through BlueOrb | Working | Filter returned four synthetic instruments | +| Synthetic-spread creation | Working | WebSocket result returned a Spark security ID | +| Named security order resolution | Working | Full path reached bridge resolution and returned `not_found` for a deliberate nonexistent security without submitting an order | +| Python contract tests | Working | Gateway and command-client focused tests pass | +| Independent releases and rollback links | Working | Versioned release directories and `current` symlinks are in use | + +## Package and team boundaries + +| Team | Owns | Interface supplied to another team | +| --- | --- | --- | +| WebSocket team | JSON-RPC contract, connection lifecycle, adapters, public server | `spark-public-websocket` wheel/image and `/v1/ws` | +| BlueOrb team | DSL engine, RSS, Python streaming client | RSS gRPC API and `blueorb-surface-python` wheel | +| Spark team | `sparkd`, command bridge, command Protobuf, generated Python client | Bridge gRPC API and `spark-command-client` wheel | + +These boundaries let each team build and release independently. The gateway +contains neither BlueOrb backend code nor Spark/Quickbus implementation code. + +## Intentionally unavailable + +- `get` +- `spark_subscriptions` +- A public request that lists books +- REST command endpoints +- Public access to Quickbus or Spark internal protobufs +- Embedding the bridge into `sparkd` +- Routing Spark commands through RSS + +## Remaining work before production deployment + +The development deployment is operational. The remaining work is production +hardening and broader command verification: + +1. Decide whether order idempotency must survive bridge restarts; it is + currently process-local. +2. For security at the ws layer add TLS, authentication, authorization, rate limiting, and network firewall + rules before exposing the service to untrusted clients. +3. Finalize how multiple users will be handled at each layer. + +Deployment and artifact creation commands are documented in +[`RELEASE_AND_DEPLOYMENT.md`](../RELEASE_AND_DEPLOYMENT.md). The public JSON-RPC +wire contract is documented in [`PROTOCOL.md`](PROTOCOL.md). diff --git a/src/client/spark_public_websocket/build-release.sh b/src/client/spark_public_websocket/build-release.sh new file mode 100755 index 000000000..e0adf9426 --- /dev/null +++ b/src/client/spark_public_websocket/build-release.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env sh +set -eu + +if [ "$#" -ne 1 ]; then + echo "usage: $0 " >&2 + exit 2 +fi + +requested_version=$1 +component_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) +python_bin=${PYTHON:-python3} +declared_version=$(sed -n 's/^version = "\([^"]*\)"/\1/p' "$component_dir/pyproject.toml") + +if [ "$requested_version" != "$declared_version" ]; then + echo "requested version $requested_version does not match pyproject.toml version $declared_version" >&2 + exit 1 +fi + +dist_dir="$component_dir/dist" +wheel_name="spark_public_websocket-$declared_version-py3-none-any.whl" +sdist_name="spark_public_websocket-$declared_version.tar.gz" +deploy_name="spark-public-websocket-deploy-$declared_version.tar.gz" + +if [ -e "$dist_dir/$wheel_name" ] || [ -e "$dist_dir/$sdist_name" ] || [ -e "$dist_dir/$deploy_name" ]; then + echo "release output already exists for $declared_version; remove it or bump the package version" >&2 + exit 1 +fi + +mkdir -p "$dist_dir" +"$python_bin" -m build --wheel --sdist --outdir "$dist_dir" "$component_dir" +tar -C "$component_dir" -czf "$dist_dir/$deploy_name" deploy +( + cd "$dist_dir" + sha256sum "$wheel_name" "$sdist_name" "$deploy_name" > "spark-public-websocket-$declared_version.sha256" +) + +echo "created $dist_dir/$wheel_name" +echo "created $dist_dir/$sdist_name" +echo "created $dist_dir/$deploy_name" diff --git a/src/client/spark_public_websocket/deploy/spark-public-websocket.env.example b/src/client/spark_public_websocket/deploy/spark-public-websocket.env.example new file mode 100644 index 000000000..5b636a7f6 --- /dev/null +++ b/src/client/spark_public_websocket/deploy/spark-public-websocket.env.example @@ -0,0 +1,4 @@ +PUBLIC_WS_HOST=0.0.0.0 +PUBLIC_WS_PORT=8090 +BLUEORB_ADDRESS=http://127.0.0.1:5085 +SPARK_COMMAND_ADDRESS=127.0.0.1:50051 diff --git a/src/client/spark_public_websocket/deploy/spark-public-websocket.service b/src/client/spark_public_websocket/deploy/spark-public-websocket.service new file mode 100644 index 000000000..98d2eeaab --- /dev/null +++ b/src/client/spark_public_websocket/deploy/spark-public-websocket.service @@ -0,0 +1,21 @@ +[Unit] +Description=Spark and BlueOrb public WebSocket gateway +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=sparkwebsocket +Group=sparkwebsocket +WorkingDirectory=/opt/spark-public-websocket/current +Environment=HOME=/var/lib/spark-public-websocket +EnvironmentFile=/etc/spark-public-websocket/spark-public-websocket.env +ExecStart=/opt/spark-public-websocket/current/bin/spark-public-websocket +Restart=on-failure +RestartSec=3 +NoNewPrivileges=true +PrivateTmp=true +StateDirectory=spark-public-websocket + +[Install] +WantedBy=multi-user.target diff --git a/src/client/spark_public_websocket/pyproject.toml b/src/client/spark_public_websocket/pyproject.toml new file mode 100644 index 000000000..cb71205ba --- /dev/null +++ b/src/client/spark_public_websocket/pyproject.toml @@ -0,0 +1,26 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "spark-public-websocket" +version = "0.1.3" +description = "Standalone public WebSocket gateway for Spark and BlueOrb" +requires-python = ">=3.10" +dependencies = [ + "blueorb-surface-python>=0.1,<0.2", + "fastapi>=0.115,<0.116", + "pydantic>=2,<3", + "spark-command-client>=0.1.2,<0.2", + "uvicorn>=0.30,<1", + "websockets>=12,<16", +] + +[project.optional-dependencies] +test = ["build>=1,<2", "httpx>=0.27,<1", "pytest>=8,<10"] + +[project.scripts] +spark-public-websocket = "spark_public_websocket.server:main" + +[tool.setuptools.packages.find] +where = ["src"] diff --git a/src/client/spark_public_websocket/src/spark_public_websocket/__init__.py b/src/client/spark_public_websocket/src/spark_public_websocket/__init__.py new file mode 100644 index 000000000..bfa3ecd0f --- /dev/null +++ b/src/client/spark_public_websocket/src/spark_public_websocket/__init__.py @@ -0,0 +1,7 @@ +"""Public WebSocket layer with independently injected Spark and BlueOrb clients.""" + +from .app import create_app +from .blueorb import BlueOrbAdapter, PublicBlueOrb +from .spark import SparkCommandAdapter + +__all__ = ["BlueOrbAdapter", "PublicBlueOrb", "SparkCommandAdapter", "create_app"] diff --git a/src/client/spark_public_websocket/src/spark_public_websocket/__main__.py b/src/client/spark_public_websocket/src/spark_public_websocket/__main__.py new file mode 100644 index 000000000..5b9eec7c5 --- /dev/null +++ b/src/client/spark_public_websocket/src/spark_public_websocket/__main__.py @@ -0,0 +1,5 @@ +from .server import main + + +if __name__ == "__main__": + main() diff --git a/src/client/spark_public_websocket/src/spark_public_websocket/app.py b/src/client/spark_public_websocket/src/spark_public_websocket/app.py new file mode 100644 index 000000000..f9bb1b8ea --- /dev/null +++ b/src/client/spark_public_websocket/src/spark_public_websocket/app.py @@ -0,0 +1,272 @@ +"""Public WebSocket gateway, with SDK and identity supplied by the host.""" + +import asyncio +import json +import logging +from contextlib import suppress +from decimal import Decimal +from typing import Any + +from fastapi import FastAPI, WebSocket, WebSocketException, status +from fastapi.encoders import jsonable_encoder +from pydantic import ValidationError + +from .blueorb import PublicBlueOrb +from .models import ( + BlueOrbSubscription, + CreateSyntheticSpread, + DeleteOrder, + EnterOrder, + Principal, + Unsubscribe, + UpdateOrder, +) +from .sdk import PublicSparkSdk, SdkError, WebSocketAuthenticator + +_LOG = logging.getLogger(__name__) +_MAX_REQUEST_BYTES = 64 * 1024 +_MAX_SUBSCRIPTIONS = 32 +_OUTGOING_QUEUE_SIZE = 256 +_JSON_RPC_ERROR_CODES = { + "invalid_json": -32700, + "invalid_request": -32600, + "method_not_found": -32601, + "invalid_params": -32602, + "internal_error": -32603, +} + + +def _wire_error(code: str, message: str) -> dict[str, Any]: + return { + "code": _JSON_RPC_ERROR_CODES.get(code, -32000), + "message": message, + "data": {"code": code}, + } + + +def create_app( + sdk: PublicSparkSdk, + authenticator: WebSocketAuthenticator, + blueorb: PublicBlueOrb | None = None, +) -> FastAPI: + """Build the public API around the already-implemented Python SDK.""" + app = FastAPI(title="Spark and BlueOrb Public WebSocket API", version="1.0") + + @app.websocket("/v1/ws") + async def websocket_api(websocket: WebSocket) -> None: + # Authentication must complete before the WebSocket is accepted. + try: + principal = await authenticator.authenticate(websocket) + except WebSocketException: + raise + except Exception as exc: + _LOG.warning("WebSocket authentication failed: %s", type(exc).__name__) + raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION) from exc + + await websocket.accept() + await _serve_connection(websocket, principal, sdk, blueorb) + + return app + + +async def _serve_connection( + websocket: WebSocket, + principal: Principal, + sdk: PublicSparkSdk, + blueorb: PublicBlueOrb | None, +) -> None: + outgoing: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=_OUTGOING_QUEUE_SIZE) + overflow = asyncio.Event() + subscriptions: dict[str, asyncio.Task[None]] = {} + + def enqueue(message: dict[str, Any]) -> None: + try: + outgoing.put_nowait(message) + except asyncio.QueueFull: + overflow.set() + + def error(request_id: str | int | None, code: str, message: str) -> None: + enqueue({"jsonrpc": "2.0", "id": request_id, "error": _wire_error(code, message)}) + + async def sender() -> None: + while True: + await websocket.send_json(await outgoing.get()) + + async def forward_blueorb(subscription_id: str, request: BlueOrbSubscription) -> None: + if blueorb is None: + return + try: + async for packet in blueorb.subscribe(principal, request): + enqueue({ + "jsonrpc": "2.0", + "method": "subscription", + "params": { + "subscription_id": subscription_id, + "packet": packet.model_dump(mode="json", by_alias=True), + }, + }) + if overflow.is_set(): + return + except asyncio.CancelledError: + # Unsubscribe is normal lifecycle, not a connection-level failure. + return + except SdkError as exc: + enqueue({ + "jsonrpc": "2.0", + "method": "subscription_error", + "params": { + "subscription_id": subscription_id, + "error": _wire_error(exc.code, exc.message), + }, + }) + except Exception: + _LOG.exception("BlueOrb subscription failed: %s", subscription_id) + enqueue({ + "jsonrpc": "2.0", + "method": "subscription_error", + "params": { + "subscription_id": subscription_id, + "error": _wire_error("internal_error", "subscription failed"), + }, + }) + finally: + if subscriptions.get(subscription_id) is asyncio.current_task(): + subscriptions.pop(subscription_id, None) + + def can_add_subscription(request_id: str | int, subscription_id: str) -> bool: + if subscription_id in subscriptions: + error(request_id, "duplicate_subscription", "subscription_id is already active") + return False + if len(subscriptions) >= _MAX_SUBSCRIPTIONS: + error(request_id, "subscription_limit", "too many subscriptions on this connection") + return False + return True + + async def dispatch(message: Any) -> None: + request_id: str | int | None = None + if isinstance(message, dict): + value = message.get("id") + if isinstance(value, (str, int)) and not isinstance(value, bool): + request_id = value + if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or request_id is None: + error(request_id, "invalid_request", "expected jsonrpc='2.0' and a string or integer id") + return + method = message.get("method") + params = message.get("params", {}) + if not isinstance(params, dict): + error(request_id, "invalid_params", "params must be an object") + return + + try: + if method == "subscription": + request = BlueOrbSubscription.model_validate(params) + if blueorb is None: + error(request_id, "backend_unavailable", "BlueOrb package is not configured") + return + if not can_add_subscription(request_id, request.subscription_id): + return + enqueue({"jsonrpc": "2.0", "id": request_id, "result": {"subscription_id": request.subscription_id}}) + subscriptions[request.subscription_id] = asyncio.create_task( + forward_blueorb(request.subscription_id, request) + ) + return + if method == "unsubscribe": + request = Unsubscribe.model_validate(params) + task = subscriptions.pop(request.subscription_id, None) + if task is None: + error(request_id, "unknown_subscription", "subscription_id is not active") + return + task.cancel() + await asyncio.gather(task, return_exceptions=True) + enqueue({"jsonrpc": "2.0", "id": request_id, "result": {"subscription_id": request.subscription_id}}) + return + if method == "unsubscribe_all": + if params: + error(request_id, "invalid_params", "unsubscribe_all does not accept params") + return + active_tasks = list(subscriptions.values()) + for task in active_tasks: + task.cancel() + subscriptions.clear() + await asyncio.gather(*active_tasks, return_exceptions=True) + enqueue({"jsonrpc": "2.0", "id": request_id, "result": {"unsubscribed": "all"}}) + return + if method == "enter_order": + result = await sdk.enter_order(principal, EnterOrder.model_validate(params)) + elif method == "update_order": + result = await sdk.update_order(principal, UpdateOrder.model_validate(params)) + elif method == "delete_order": + result = await sdk.delete_order(principal, DeleteOrder.model_validate(params)) + elif method == "create_synthetic_spread": + result = await sdk.create_synthetic_spread( + principal, CreateSyntheticSpread.model_validate(params) + ) + elif method == "ping": + if params: + error(request_id, "invalid_params", "ping does not accept params") + return + result = {"pong": True} + else: + error(request_id, "method_not_found", "unknown method") + return + enqueue({ + "jsonrpc": "2.0", + "id": request_id, + "result": jsonable_encoder(result, custom_encoder={Decimal: str}), + }) + except ValidationError as exc: + fields = [".".join(map(str, item["loc"])) for item in exc.errors()] + error(request_id, "invalid_params", "invalid fields: " + ", ".join(fields)) + except SdkError as exc: + error(request_id, exc.code, exc.message) + except Exception: + _LOG.exception("Public WebSocket request failed: %s", method) + error(request_id, "internal_error", "request failed") + + send_task = asyncio.create_task(sender()) + overflow_task = asyncio.create_task(overflow.wait()) + receive_task: asyncio.Task[dict[str, Any]] | None = None + try: + while True: + receive_task = asyncio.create_task(websocket.receive()) + done, _ = await asyncio.wait( + {receive_task, send_task, overflow_task}, return_when=asyncio.FIRST_COMPLETED + ) + if overflow_task in done: + receive_task.cancel() + with suppress(RuntimeError): + await websocket.close(code=1013, reason="client too slow") + break + if send_task in done: + receive_task.cancel() + break + frame = receive_task.result() + if frame["type"] == "websocket.disconnect": + break + raw = frame.get("text") + if raw is None: + await websocket.close(code=1003, reason="text frames only") + break + if len(raw.encode("utf-8")) > _MAX_REQUEST_BYTES: + error(None, "request_too_large", "request exceeds 64 KiB") + continue + try: + await dispatch(json.loads(raw)) + except json.JSONDecodeError: + error(None, "invalid_json", "request is not valid JSON") + except asyncio.CancelledError: + # ASGI servers may cancel the connection coroutine as part of a normal + # client disconnect or shutdown. Cleanup below owns child cancellation. + pass + finally: + cleanup_tasks: list[asyncio.Task[Any]] = [] + if receive_task is not None and not receive_task.done(): + receive_task.cancel() + cleanup_tasks.append(receive_task) + for task in subscriptions.values(): + task.cancel() + send_task.cancel() + overflow_task.cancel() + cleanup_tasks.extend(subscriptions.values()) + cleanup_tasks.extend((send_task, overflow_task)) + await asyncio.gather(*cleanup_tasks, return_exceptions=True) diff --git a/src/client/spark_public_websocket/src/spark_public_websocket/blueorb.py b/src/client/spark_public_websocket/src/spark_public_websocket/blueorb.py new file mode 100644 index 000000000..8c5dd0cbb --- /dev/null +++ b/src/client/spark_public_websocket/src/spark_public_websocket/blueorb.py @@ -0,0 +1,163 @@ +"""Async boundary around the independently packaged BlueOrb Python surface.""" + +import asyncio +import logging +from collections.abc import AsyncIterator, Callable +from threading import Event +from typing import Any, Protocol + +from .models import ( + BlueOrbColumn, + BlueOrbPacket, + BlueOrbSchema, + BlueOrbSubscription, + Principal, +) +from .sdk import SdkError + +_LOG = logging.getLogger(__name__) +_PACKET_QUEUE_SIZE = 64 + + +class BlockingBlueOrbHost(Protocol): + """The public subset supplied by blueorb-surface-python.""" + + def subscribe( + self, + dsl: str, + callback: Callable[[Any], None], + cancellation_event: Event | None = None, + ) -> None: ... + + +class PublicBlueOrb(Protocol): + """Async interface consumed by the WebSocket transport.""" + + def subscribe( + self, + principal: Principal, + request: BlueOrbSubscription, + ) -> AsyncIterator[BlueOrbPacket]: ... + + +class BlueOrbAdapter: + """Runs BlueOrb's blocking callback API without blocking the ASGI loop.""" + + def __init__(self, host: BlockingBlueOrbHost) -> None: + self._host = host + + async def subscribe( + self, + principal: Principal, + request: BlueOrbSubscription, + ) -> AsyncIterator[BlueOrbPacket]: + # Keep identity in this interface even though unrestricted BlueOrb does + # not consume it yet, so authorization can be added without a redesign. + del principal + + loop = asyncio.get_running_loop() + packets: asyncio.Queue[BlueOrbPacket] = asyncio.Queue(maxsize=_PACKET_QUEUE_SIZE) + stopped = Event() + finished = asyncio.Event() + worker_error: list[Exception] = [] + + def offer(packet: Any) -> None: + if stopped.is_set(): + return + try: + packets.put_nowait(_to_public_packet(packet)) + except asyncio.QueueFull: + worker_error.append( + SdkError("blueorb_backpressure", "BlueOrb packet consumer is too slow") + ) + stopped.set() + finished.set() + except Exception as exc: + worker_error.append(exc) + stopped.set() + finished.set() + + def on_packet(packet: Any) -> None: + loop.call_soon_threadsafe(offer, packet) + + def run() -> None: + try: + self._host.subscribe(request.dsl, on_packet, stopped) + except Exception as exc: + loop.call_soon_threadsafe(worker_error.append, exc) + finally: + loop.call_soon_threadsafe(finished.set) + + worker = asyncio.create_task(asyncio.to_thread(run)) + try: + while True: + if finished.is_set() and packets.empty(): + if worker_error: + raise _translate_error(worker_error[0]) + return + + packet_task = asyncio.create_task(packets.get()) + finished_task = asyncio.create_task(finished.wait()) + done, pending = await asyncio.wait( + {packet_task, finished_task}, + return_when=asyncio.FIRST_COMPLETED, + ) + for task in pending: + task.cancel() + await asyncio.gather(*pending, return_exceptions=True) + + if packet_task in done: + yield packet_task.result() + finally: + stopped.set() + try: + await asyncio.wait_for(asyncio.shield(worker), timeout=2) + except TimeoutError: + _LOG.warning("Timed out waiting for BlueOrb subscription cancellation") + except asyncio.CancelledError: + pass + except Exception: + # The iterator loop reports a translated form of worker errors. + pass + + +def _to_public_packet(packet: Any) -> BlueOrbPacket: + schema = BlueOrbSchema( + name=packet.schema.name, + columns=[ + BlueOrbColumn( + name=column.name, + ordinal=column.ordinal, + type_code=column.type_code, + nullable=column.nullable, + ) + for column in packet.schema.columns + ], + ) + return BlueOrbPacket( + table=packet.table, + schema=schema, + current=packet.current, + added=packet.added, + removed=packet.removed, + kind=packet.kind, + sequence=packet.sequence, + ) + + +def _translate_error(error: Exception) -> SdkError: + if isinstance(error, SdkError): + return error + + grpc_code = getattr(error, "code", None) + if callable(grpc_code): + code_value = grpc_code() + code_name = getattr(code_value, "name", str(code_value)) + if code_name == "INVALID_ARGUMENT": + return SdkError("invalid_blueorb_query", str(error)) + if code_name in {"UNAVAILABLE", "DEADLINE_EXCEEDED"}: + return SdkError("backend_unavailable", "BlueOrb RemoteStreamServer is unavailable") + if code_name == "CANCELLED": + return SdkError("subscription_cancelled", "BlueOrb subscription was cancelled") + + return SdkError("blueorb_error", str(error) or type(error).__name__) diff --git a/src/client/spark_public_websocket/src/spark_public_websocket/models.py b/src/client/spark_public_websocket/src/spark_public_websocket/models.py new file mode 100644 index 000000000..a502dec63 --- /dev/null +++ b/src/client/spark_public_websocket/src/spark_public_websocket/models.py @@ -0,0 +1,204 @@ +"""Public v1 wire models, independent of Spark's internal protobuf messages.""" + +from decimal import Decimal +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + + +class WireModel(BaseModel): + model_config = ConfigDict(extra="forbid") + + +BlueOrbPacketKind = Literal["snapshot", "delta"] + + +class Principal(WireModel): + subject: str + + +class BlueOrbSubscription(WireModel): + subscription_id: str = Field(min_length=1, max_length=128) + dsl: str = Field(min_length=1, max_length=8192) + + +class BlueOrbColumn(WireModel): + name: str + ordinal: int = Field(ge=0) + type_code: str + nullable: bool + + +class BlueOrbSchema(WireModel): + name: str + columns: list[BlueOrbColumn] + + +class BlueOrbPacket(WireModel): + table: str + stream_schema: BlueOrbSchema = Field(alias="schema", serialization_alias="schema") + current: list[dict[str, Any]] + added: list[dict[str, Any]] + removed: list[dict[str, Any]] + kind: BlueOrbPacketKind + sequence: int = Field(ge=0) + + +class Unsubscribe(WireModel): + subscription_id: str = Field(min_length=1) + + +class EnterOrder(WireModel): + client_order_id: str = Field(min_length=1) + account: str = Field(min_length=1) + security_id: str | None = Field(default=None, min_length=1) + exchange: str | None = Field(default=None, min_length=1) + exchange_security_name: str | None = Field(default=None, min_length=1) + side: Literal["buy", "sell"] + order_type: Literal["market", "limit"] + quantity: Decimal = Field(gt=0, allow_inf_nan=False) + price: Decimal | None = Field(default=None, gt=0, allow_inf_nan=False) + + @field_validator("quantity", "price", mode="before") + @classmethod + def require_decimal_string(cls, value: Any) -> Any: + if value is not None and not isinstance(value, str): + raise ValueError("decimal values must be strings") + return value + + @model_validator(mode="after") + def check_price(self) -> "EnterOrder": + has_id = self.security_id is not None + has_exchange = self.exchange is not None + has_name = self.exchange_security_name is not None + if has_id and (has_exchange or has_name): + raise ValueError( + "use either security_id or exchange/exchange_security_name" + ) + if not has_id and not (has_exchange and has_name): + raise ValueError( + "security_id or exchange and exchange_security_name are required" + ) + if self.order_type == "limit" and self.price is None: + raise ValueError("limit orders require price") + if self.order_type == "market" and self.price is not None: + raise ValueError("market orders cannot include price") + return self + + +class UpdateOrder(WireModel): + order_id: str = Field(min_length=1) + quantity: Decimal | None = Field(default=None, gt=0, allow_inf_nan=False) + price: Decimal | None = Field(default=None, gt=0, allow_inf_nan=False) + + @field_validator("quantity", "price", mode="before") + @classmethod + def require_decimal_string(cls, value: Any) -> Any: + if value is not None and not isinstance(value, str): + raise ValueError("decimal values must be strings") + return value + + @model_validator(mode="after") + def require_change(self) -> "UpdateOrder": + if self.quantity is None and self.price is None: + raise ValueError("quantity or price is required") + return self + + +class DeleteOrder(WireModel): + order_id: str = Field(min_length=1) + + +class CreateSyntheticSpread(WireModel): + """Public synthetic-spread request; omitted overrides use SDK/backend presets.""" + + leg1_security_id: str | None = Field(default=None, min_length=1) + leg1_exchange: str | None = Field(default=None, min_length=1) + leg1_exchange_security_name: str | None = Field(default=None, min_length=1) + leg2_security_id: str | None = Field(default=None, min_length=1) + leg2_exchange: str | None = Field(default=None, min_length=1) + leg2_exchange_security_name: str | None = Field(default=None, min_length=1) + + name: str | None = Field(default=None, min_length=1) + symbol: str | None = Field(default=None, min_length=1) + currency: str | None = Field(default=None, min_length=1) + tick_size: Decimal | None = Field(default=None, gt=0, allow_inf_nan=False) + cash_per_point: Decimal | None = Field(default=None, gt=0, allow_inf_nan=False) + price_multiplier: Decimal | None = Field(default=None, gt=0, allow_inf_nan=False) + main_fraction: int | None = Field(default=None, gt=0) + sub_fraction: int | None = Field(default=None, gt=0) + price_display_format: int | None = Field(default=None, ge=0) + price_calc: Literal["standard", "net_change", "notional_leg"] | None = None + + cancel_hedges_on_cancel: bool | None = None + hedge_pricing: Literal["cached_drivers", "recalculate_crosses"] | None = None + spreader_type: Literal["requote", "reverse_hedge", "sniper"] | None = None + lean_quantity_ratio: Decimal | None = Field(default=None, gt=0, allow_inf_nan=False) + + leg1_quantity: Decimal | None = Field(default=None, gt=0, allow_inf_nan=False) + leg1_price_multiplier: Decimal | None = Field(default=None, allow_inf_nan=False) + leg1_leg_delta: Decimal | None = Field(default=None, allow_inf_nan=False) + leg1_side: Literal["buy", "sell"] | None = None + leg1_is_active_quoting: bool | None = None + leg1_enable_hedging: bool | None = None + leg1_market_data_type: Literal["merged", "direct"] | None = None + + leg2_quantity: Decimal | None = Field(default=None, gt=0, allow_inf_nan=False) + leg2_price_multiplier: Decimal | None = Field(default=None, allow_inf_nan=False) + leg2_leg_delta: Decimal | None = Field(default=None, allow_inf_nan=False) + leg2_side: Literal["buy", "sell"] | None = None + leg2_is_active_quoting: bool | None = None + leg2_enable_hedging: bool | None = None + leg2_market_data_type: Literal["merged", "direct"] | None = None + + @field_validator( + "tick_size", + "cash_per_point", + "price_multiplier", + "lean_quantity_ratio", + "leg1_quantity", + "leg1_price_multiplier", + "leg1_leg_delta", + "leg2_quantity", + "leg2_price_multiplier", + "leg2_leg_delta", + mode="before", + ) + @classmethod + def require_decimal_string(cls, value: Any) -> Any: + if value is not None and not isinstance(value, str): + raise ValueError("decimal values must be strings") + return value + + @field_validator("leg1_price_multiplier", "leg2_price_multiplier") + @classmethod + def require_nonzero_leg_multiplier(cls, value: Decimal | None) -> Decimal | None: + if value == 0: + raise ValueError("leg price multipliers cannot be zero") + return value + + @model_validator(mode="after") + def require_leg_locators(self) -> "CreateSyntheticSpread": + for prefix in ("leg1", "leg2"): + security_id = getattr(self, f"{prefix}_security_id") + exchange = getattr(self, f"{prefix}_exchange") + name = getattr(self, f"{prefix}_exchange_security_name") + if security_id is not None and (exchange is not None or name is not None): + raise ValueError( + f"{prefix} must use either security_id or exchange/exchange_security_name" + ) + if security_id is None and (exchange is None or name is None): + raise ValueError( + f"{prefix} requires security_id or exchange and exchange_security_name" + ) + return self + + +class CreateSyntheticSpreadResult(WireModel): + security_id: str = Field(min_length=1) + + +class OrderResult(WireModel): + order_id: str + status: Literal["accepted", "pending", "rejected"] + message: str | None = None diff --git a/src/client/spark_public_websocket/src/spark_public_websocket/sdk.py b/src/client/spark_public_websocket/src/spark_public_websocket/sdk.py new file mode 100644 index 000000000..3e06bf6eb --- /dev/null +++ b/src/client/spark_public_websocket/src/spark_public_websocket/sdk.py @@ -0,0 +1,40 @@ +"""The narrow SDK contract required by this gateway. + +The actual Python SDK and bridge are provided by a different project. +""" + +from typing import Protocol + +from fastapi import WebSocket + +from .models import ( + CreateSyntheticSpread, + CreateSyntheticSpreadResult, + DeleteOrder, + EnterOrder, + OrderResult, + Principal, + UpdateOrder, +) + + +class SdkError(Exception): + def __init__(self, code: str, message: str): + super().__init__(message) + self.code = code + self.message = message + + +class PublicSparkSdk(Protocol): + """Implementations enforce Spark permissions for the supplied principal.""" + + async def enter_order(self, principal: Principal, request: EnterOrder) -> OrderResult: ... + async def update_order(self, principal: Principal, request: UpdateOrder) -> OrderResult: ... + async def delete_order(self, principal: Principal, request: DeleteOrder) -> OrderResult: ... + async def create_synthetic_spread( + self, principal: Principal, request: CreateSyntheticSpread + ) -> CreateSyntheticSpreadResult: ... + + +class WebSocketAuthenticator(Protocol): + async def authenticate(self, websocket: WebSocket) -> Principal: ... diff --git a/src/client/spark_public_websocket/src/spark_public_websocket/server.py b/src/client/spark_public_websocket/src/spark_public_websocket/server.py new file mode 100644 index 000000000..9a35a4c10 --- /dev/null +++ b/src/client/spark_public_websocket/src/spark_public_websocket/server.py @@ -0,0 +1,144 @@ +"""Runnable development host for the independently packaged gateway.""" + +import argparse +import importlib +import logging +import os +from collections.abc import Callable +from typing import Any + +from fastapi import WebSocket + +from .app import create_app +from .blueorb import BlueOrbAdapter, PublicBlueOrb +from .models import Principal +from .sdk import SdkError +from .spark import SparkCommandAdapter + +_LOG = logging.getLogger(__name__) + + +class AnonymousAuthenticator: + """Development identity used while external authentication is out of scope.""" + + async def authenticate(self, websocket: WebSocket) -> Principal: + del websocket + return Principal(subject="anonymous") + + +class UnavailableSparkSdk: + """Allows BlueOrb and local protocol work without sparkd or a Spark SDK.""" + + async def enter_order(self, principal: Principal, request: Any) -> Any: + self._unavailable(principal, request) + + async def update_order(self, principal: Principal, request: Any) -> Any: + self._unavailable(principal, request) + + async def delete_order(self, principal: Principal, request: Any) -> Any: + self._unavailable(principal, request) + + async def create_synthetic_spread(self, principal: Principal, request: Any) -> Any: + self._unavailable(principal, request) + + @staticmethod + def _unavailable(principal: Principal, request: Any) -> None: + del principal, request + raise SdkError("backend_unavailable", "Spark SDK is not configured") + + +def create_runtime_app( + blueorb_address: str | None = "http://localhost:5085", + spark_sdk_factory: str | None = None, + spark_command_address: str | None = "127.0.0.1:50051", +) -> Any: + """Create a server that can run with BlueOrb even when Spark is absent.""" + if spark_sdk_factory: + sdk = _load_factory(spark_sdk_factory) + elif spark_command_address: + sdk = _create_spark(spark_command_address) + else: + sdk = UnavailableSparkSdk() + blueorb = _create_blueorb(blueorb_address) + return create_app(sdk, AnonymousAuthenticator(), blueorb) + + +def _create_spark(address: str) -> SparkCommandAdapter: + try: + from spark_command_client import SparkCommandClient + except ImportError as exc: + raise RuntimeError( + "Spark commands are enabled but spark-command-client is not installed" + ) from exc + return SparkCommandAdapter(SparkCommandClient(address)) + + +def _create_blueorb(address: str | None) -> PublicBlueOrb | None: + if not address: + return None + try: + from blueorb import BlueOrbStreamHost + except ImportError as exc: + raise RuntimeError( + "BlueOrb is enabled but blueorb-surface-python is not installed" + ) from exc + return BlueOrbAdapter(BlueOrbStreamHost(address)) + + +def _load_factory(specification: str) -> Any: + module_name, separator, attribute_name = specification.partition(":") + if not separator or not module_name or not attribute_name: + raise ValueError("Spark SDK factory must use module:function syntax") + module = importlib.import_module(module_name) + factory = getattr(module, attribute_name) + if not isinstance(factory, Callable): + raise TypeError(f"Spark SDK factory '{specification}' is not callable") + return factory() + + +def main() -> None: + parser = argparse.ArgumentParser(description="Run the public Python WebSocket gateway") + parser.add_argument("--host", default=os.environ.get("PUBLIC_WS_HOST", "127.0.0.1")) + parser.add_argument( + "--port", + type=int, + default=int(os.environ.get("PUBLIC_WS_PORT", "8090")), + ) + parser.add_argument( + "--blueorb-address", + default=os.environ.get("BLUEORB_ADDRESS", "http://localhost:5085"), + ) + parser.add_argument( + "--without-blueorb", + action="store_true", + help="Disable the BlueOrb integration for this server process", + ) + parser.add_argument( + "--spark-sdk-factory", + default=os.environ.get("SPARK_SDK_FACTORY"), + help="Optional module:function returning a PublicSparkSdk implementation", + ) + parser.add_argument( + "--spark-command-address", + default=os.environ.get("SPARK_COMMAND_ADDRESS", "127.0.0.1:50051"), + help="Spark command bridge gRPC authority", + ) + parser.add_argument( + "--without-spark", + action="store_true", + help="Disable Spark commands for isolated BlueOrb/protocol development", + ) + parser.add_argument("--log-level", default="info") + args = parser.parse_args() + + try: + import uvicorn + except ImportError as exc: # pragma: no cover - packaging failure + raise RuntimeError("Install the server dependencies for uvicorn support") from exc + + app = create_runtime_app( + blueorb_address=None if args.without_blueorb else args.blueorb_address, + spark_sdk_factory=args.spark_sdk_factory, + spark_command_address=None if args.without_spark else args.spark_command_address, + ) + uvicorn.run(app, host=args.host, port=args.port, log_level=args.log_level) diff --git a/src/client/spark_public_websocket/src/spark_public_websocket/spark.py b/src/client/spark_public_websocket/src/spark_public_websocket/spark.py new file mode 100644 index 000000000..710c2ab50 --- /dev/null +++ b/src/client/spark_public_websocket/src/spark_public_websocket/spark.py @@ -0,0 +1,55 @@ +"""Adapter from the independently packaged bridge client to gateway models.""" + +from typing import Any + +from spark_command_client import BridgeError, SparkCommandClient + +from .models import ( + CreateSyntheticSpread, + CreateSyntheticSpreadResult, + DeleteOrder, + EnterOrder, + OrderResult, + Principal, + UpdateOrder, +) +from .sdk import SdkError + + +class SparkCommandAdapter: + def __init__(self, client: SparkCommandClient): + self._client = client + + async def enter_order( + self, principal: Principal, request: EnterOrder + ) -> OrderResult: + del principal + return OrderResult.model_validate(await self._invoke(self._client.enter_order, request)) + + async def update_order( + self, principal: Principal, request: UpdateOrder + ) -> OrderResult: + del principal + return OrderResult.model_validate(await self._invoke(self._client.update_order, request)) + + async def delete_order( + self, principal: Principal, request: DeleteOrder + ) -> OrderResult: + del principal + return OrderResult.model_validate(await self._invoke(self._client.delete_order, request)) + + async def create_synthetic_spread( + self, + principal: Principal, + request: CreateSyntheticSpread, + ) -> CreateSyntheticSpreadResult: + del principal + result = await self._invoke(self._client.create_synthetic_spread, request) + return CreateSyntheticSpreadResult.model_validate(result) + + @staticmethod + async def _invoke(operation: Any, request: Any) -> Any: + try: + return await operation(request) + except BridgeError as exc: + raise SdkError(exc.code, exc.message) from exc diff --git a/src/client/spark_public_websocket/tests/test_app.py b/src/client/spark_public_websocket/tests/test_app.py new file mode 100644 index 000000000..7bb93cce4 --- /dev/null +++ b/src/client/spark_public_websocket/tests/test_app.py @@ -0,0 +1,228 @@ +"""Contract tests with an in-memory SDK; no Spark bridge is required.""" + +import asyncio +from contextlib import contextmanager +from decimal import Decimal + +from fastapi.testclient import TestClient + +from spark_public_websocket import create_app +from spark_public_websocket.models import ( + BlueOrbColumn, + BlueOrbPacket, + BlueOrbSchema, + CreateSyntheticSpreadResult, + OrderResult, + Principal, +) + + +class TestAuthenticator: + async def authenticate(self, websocket): + return Principal(subject="test-user") + + +class FakeSdk: + def __init__(self): + self.orders = [] + self.synthetic_spreads = [] + + async def enter_order(self, principal, request): + self.orders.append((principal, request)) + return OrderResult(order_id="ord-1", status="pending") + + async def update_order(self, principal, request): + return OrderResult(order_id=request.order_id, status="pending") + + async def delete_order(self, principal, request): + return OrderResult(order_id=request.order_id, status="pending") + + async def create_synthetic_spread(self, principal, request): + self.synthetic_spreads.append((principal, request)) + return CreateSyntheticSpreadResult(security_id="sec-synthetic-1") + +class FakeBlueOrb: + async def subscribe(self, principal, request): + assert principal.subject == "test-user" + assert request.dsl == 'phoenix_bbo("SOL")' + yield BlueOrbPacket( + table="phoenix_bbo", + schema=BlueOrbSchema( + name="phoenix_bbo", + columns=[ + BlueOrbColumn( + name="price", + ordinal=0, + type_code="decimal", + nullable=False, + ) + ], + ), + current=[{"price": Decimal("100.25")}], + added=[{"price": Decimal("100.25")}], + removed=[], + kind="snapshot", + sequence=1, + ) + await asyncio.Event().wait() + + +def client_for(sdk, blueorb=None): + return TestClient(create_app(sdk, TestAuthenticator(), blueorb)) + + +@contextmanager +def websocket_for(sdk, blueorb=None): + with client_for(sdk, blueorb) as client: + with client.websocket_connect("/v1/ws") as websocket: + yield websocket + + +def test_blueorb_subscription_ack_packet_and_unsubscribe(): + with websocket_for(FakeSdk(), FakeBlueOrb()) as ws: + ws.send_json({ + "jsonrpc": "2.0", + "id": "query", + "method": "subscription", + "params": { + "subscription_id": "blueorb-1", + "dsl": 'phoenix_bbo("SOL")', + }, + }) + assert ws.receive_json() == { + "jsonrpc": "2.0", + "id": "query", + "result": {"subscription_id": "blueorb-1"}, + } + event = ws.receive_json() + assert event["method"] == "subscription" + assert event["params"]["packet"]["kind"] == "snapshot" + assert "schema" in event["params"]["packet"] + assert "stream_schema" not in event["params"]["packet"] + assert event["params"]["packet"]["current"][0]["price"] == "100.25" + + ws.send_json({ + "jsonrpc": "2.0", + "id": "stop", + "method": "unsubscribe", + "params": {"subscription_id": "blueorb-1"}, + }) + assert ws.receive_json()["result"] == {"subscription_id": "blueorb-1"} + + +def test_blueorb_subscription_requires_configured_package(): + with websocket_for(FakeSdk()) as ws: + ws.send_json({ + "jsonrpc": "2.0", + "id": "query", + "method": "subscription", + "params": {"subscription_id": "blueorb-1", "dsl": "stream_docs()"}, + }) + error = ws.receive_json()["error"] + assert error["data"]["code"] == "backend_unavailable" + + +def test_order_validation_and_identity(): + sdk = FakeSdk() + with websocket_for(sdk) as ws: + params = {"client_order_id": "client-1", "account": "acc-1", "security_id": "sec-1", + "side": "buy", "order_type": "limit", "quantity": "2", "price": "100.25"} + ws.send_json({"jsonrpc": "2.0", "id": "order", "method": "enter_order", "params": params}) + assert ws.receive_json()["result"]["order_id"] == "ord-1" + principal, request = sdk.orders[0] + assert principal.subject == "test-user" + assert request.price == Decimal("100.25") + + ws.send_json({"jsonrpc": "2.0", "id": "bad", "method": "enter_order", + "params": {**params, "price": 100.25}}) + assert ws.receive_json()["error"]["data"]["code"] == "invalid_params" + assert len(sdk.orders) == 1 + + +def test_enter_order_accepts_exchange_security_name(): + sdk = FakeSdk() + with websocket_for(sdk) as ws: + ws.send_json({ + "jsonrpc": "2.0", + "id": "named-order", + "method": "enter_order", + "params": { + "client_order_id": "client-named-1", + "account": "ACC A", + "exchange": "okx", + "exchange_security_name": "SOL-USDC", + "side": "buy", + "order_type": "limit", + "quantity": "1", + "price": "1.00", + }, + }) + assert ws.receive_json()["result"]["order_id"] == "ord-1" + request = sdk.orders[0][1] + assert request.security_id is None + assert request.exchange == "okx" + assert request.exchange_security_name == "SOL-USDC" + + +def test_removed_and_unknown_methods_are_rejected(): + with websocket_for(FakeSdk()) as ws: + for request_id, method in enumerate(("get", "spark_subscriptions", "arbitrary"), 1): + ws.send_json({"jsonrpc": "2.0", "id": request_id, "method": method, "params": {}}) + error = ws.receive_json()["error"] + assert error["code"] == -32601 + assert error["data"]["code"] == "method_not_found" + + +def test_create_synthetic_spread_validation_and_identity(): + sdk = FakeSdk() + with websocket_for(sdk) as ws: + params = { + "leg1_security_id": "sec-1", + "leg2_security_id": "sec-2", + "tick_size": "0.01", + "leg1_quantity": "2", + "leg2_price_multiplier": "-1", + "spreader_type": "requote", + } + ws.send_json({ + "jsonrpc": "2.0", + "id": "spread", + "method": "create_synthetic_spread", + "params": params, + }) + assert ws.receive_json()["result"] == {"security_id": "sec-synthetic-1"} + principal, request = sdk.synthetic_spreads[0] + assert principal.subject == "test-user" + assert request.tick_size == Decimal("0.01") + assert request.leg2_price_multiplier == Decimal("-1") + + ws.send_json({ + "jsonrpc": "2.0", + "id": "bad-spread", + "method": "create_synthetic_spread", + "params": {**params, "tick_size": 0.01}, + }) + assert ws.receive_json()["error"]["data"]["code"] == "invalid_params" + assert len(sdk.synthetic_spreads) == 1 + + +def test_create_synthetic_spread_accepts_exchange_security_names(): + sdk = FakeSdk() + with websocket_for(sdk) as ws: + ws.send_json({ + "jsonrpc": "2.0", + "id": "named-spread", + "method": "create_synthetic_spread", + "params": { + "leg1_exchange": "okx", + "leg1_exchange_security_name": "SOL-USDC", + "leg2_exchange": "orca", + "leg2_exchange_security_name": "SOL-USDC-1", + }, + }) + assert ws.receive_json()["result"] == {"security_id": "sec-synthetic-1"} + request = sdk.synthetic_spreads[0][1] + assert request.leg1_exchange == "okx" + assert request.leg1_exchange_security_name == "SOL-USDC" + assert request.leg2_exchange == "orca" + assert request.leg2_exchange_security_name == "SOL-USDC-1" diff --git a/src/client/spark_public_websocket/tests/test_blueorb.py b/src/client/spark_public_websocket/tests/test_blueorb.py new file mode 100644 index 000000000..49444fe7e --- /dev/null +++ b/src/client/spark_public_websocket/tests/test_blueorb.py @@ -0,0 +1,58 @@ +"""Tests for the blocking BlueOrb callback to asyncio adapter.""" + +import asyncio +from decimal import Decimal +from types import SimpleNamespace + +from spark_public_websocket.blueorb import BlueOrbAdapter +from spark_public_websocket.models import BlueOrbSubscription, Principal + + +class BlockingFakeHost: + def __init__(self): + self.cancelled = False + + def subscribe(self, dsl, callback, cancellation_event=None): + assert dsl == 'phoenix_bbo("SOL")' + callback(SimpleNamespace( + table="phoenix_bbo", + schema=SimpleNamespace( + name="phoenix_bbo", + columns=[SimpleNamespace( + name="price", + ordinal=0, + type_code="decimal", + nullable=False, + )], + ), + current=[{"price": Decimal("100.25")}], + added=[{"price": Decimal("100.25")}], + removed=[], + kind="snapshot", + sequence=1, + )) + if cancellation_event is not None: + cancellation_event.wait(timeout=2) + self.cancelled = cancellation_event.is_set() + + +def test_adapter_maps_packet_and_cancels_blocking_subscription(): + async def run(): + host = BlockingFakeHost() + adapter = BlueOrbAdapter(host) + stream = adapter.subscribe( + Principal(subject="test-user"), + BlueOrbSubscription( + subscription_id="blueorb-1", + dsl='phoenix_bbo("SOL")', + ), + ) + + packet = await anext(stream) + assert packet.table == "phoenix_bbo" + assert packet.current == [{"price": Decimal("100.25")}] + + await stream.aclose() + assert host.cancelled + + asyncio.run(run()) diff --git a/src/client/spark_public_websocket/tests/test_blueorb_package_integration.py b/src/client/spark_public_websocket/tests/test_blueorb_package_integration.py new file mode 100644 index 000000000..80bd317e6 --- /dev/null +++ b/src/client/spark_public_websocket/tests/test_blueorb_package_integration.py @@ -0,0 +1,103 @@ +"""Full Python path: WebSocket -> BlueOrb package -> gRPC stream -> packet.""" + +import time +from concurrent.futures import ThreadPoolExecutor + +import grpc +from blueorb.protocol import ( + RemoteStreamPacket, + RemoteStreamSubscribeRequest, +) +from fastapi.testclient import TestClient + +from spark_public_websocket.server import create_runtime_app + + +def _remote_packet(): + packet = RemoteStreamPacket( + remote_stream_id="integration-stream", + sequence=1, + kind=1, + ) + packet.payload.schema.name = "integration_values" + + id_column = packet.payload.schema.columns.add() + id_column.name = "id" + id_column.ordinal = 0 + id_column.type_code = 9 + id_column.nullable = False + + value_column = packet.payload.schema.columns.add() + value_column.name = "value" + value_column.ordinal = 1 + value_column.type_code = 15 + value_column.nullable = False + + row = packet.payload.current.rows.add() + row.values.add().int32_value = 1 + row.values.add().decimal_value = "100.25" + packet.payload.added.CopyFrom(packet.payload.current) + return packet + + +def test_real_blueorb_package_streams_a_grpc_packet_through_websocket(): + grpc_server = grpc.server(ThreadPoolExecutor(max_workers=1)) + + def subscribe(request, context): + assert request.dsl == 'literal("integration_values", {id = 1, value = 100.25})' + yield _remote_packet() + while context.is_active(): + time.sleep(0.01) + + handler = grpc.unary_stream_rpc_method_handler( + subscribe, + request_deserializer=RemoteStreamSubscribeRequest.FromString, + response_serializer=RemoteStreamPacket.SerializeToString, + ) + grpc_server.add_generic_rpc_handlers(( + grpc.method_handlers_generic_handler( + "remotestream.RemoteStreamTransport", + {"Subscribe": handler}, + ), + )) + port = grpc_server.add_insecure_port("127.0.0.1:0") + grpc_server.start() + + app = create_runtime_app(blueorb_address=f"http://127.0.0.1:{port}") + try: + with TestClient(app) as client: + with client.websocket_connect("/v1/ws") as websocket: + websocket.send_json({ + "jsonrpc": "2.0", + "id": "start", + "method": "subscription", + "params": { + "subscription_id": "blueorb-integration", + "dsl": 'literal("integration_values", {id = 1, value = 100.25})', + }, + }) + assert websocket.receive_json() == { + "jsonrpc": "2.0", + "id": "start", + "result": {"subscription_id": "blueorb-integration"}, + } + + event = websocket.receive_json() + assert event["method"] == "subscription" + assert event["params"]["subscription_id"] == "blueorb-integration" + assert event["params"]["packet"]["table"] == "integration_values" + assert event["params"]["packet"]["current"] == [ + {"id": 1, "value": "100.25"} + ] + + websocket.send_json({ + "jsonrpc": "2.0", + "id": "stop", + "method": "unsubscribe", + "params": {"subscription_id": "blueorb-integration"}, + }) + assert websocket.receive_json()["result"] == { + "subscription_id": "blueorb-integration" + } + finally: + grpc_server.stop(grace=0).wait() diff --git a/src/client/spark_public_websocket/tests/test_spark_command_package_integration.py b/src/client/spark_public_websocket/tests/test_spark_command_package_integration.py new file mode 100644 index 000000000..3840595d0 --- /dev/null +++ b/src/client/spark_public_websocket/tests/test_spark_command_package_integration.py @@ -0,0 +1,71 @@ +"""WebSocket -> packaged client -> gRPC bridge contract integration.""" + +from concurrent.futures import ThreadPoolExecutor + +import grpc +from fastapi.testclient import TestClient +from spark_command_client import SparkCommandClient +from spark_command_client.generated import spark_command_pb2 as messages +from spark_command_client.generated import spark_command_pb2_grpc as services + +from spark_public_websocket import SparkCommandAdapter, create_app +from spark_public_websocket.models import Principal + + +class TestAuthenticator: + async def authenticate(self, websocket): + return Principal(subject="integration-user") + + +class FakeCommandBridge(services.SparkCommandServiceServicer): + def __init__(self): + self.request = None + + def EnterOrder(self, request, context): + self.request = request + return messages.OrderResult( + order_id="9001", + status=messages.COMMAND_STATUS_ACCEPTED, + ) + + +def test_order_crosses_websocket_package_and_grpc_contract(): + bridge = FakeCommandBridge() + grpc_server = grpc.server(ThreadPoolExecutor(max_workers=1)) + services.add_SparkCommandServiceServicer_to_server(bridge, grpc_server) + port = grpc_server.add_insecure_port("127.0.0.1:0") + grpc_server.start() + + sdk = SparkCommandAdapter(SparkCommandClient(f"127.0.0.1:{port}")) + app = create_app(sdk, TestAuthenticator()) + try: + with TestClient(app) as client: + with client.websocket_connect("/v1/ws") as websocket: + websocket.send_json({ + "jsonrpc": "2.0", + "id": "enter", + "method": "enter_order", + "params": { + "client_order_id": "client-9001", + "account": "ACC-A", + "security_id": "42", + "side": "buy", + "order_type": "limit", + "quantity": "2", + "price": "100.25", + }, + }) + assert websocket.receive_json() == { + "jsonrpc": "2.0", + "id": "enter", + "result": { + "order_id": "9001", + "status": "accepted", + "message": None, + }, + } + assert bridge.request.client_order_id == "client-9001" + assert bridge.request.security_id == "42" + assert bridge.request.price == "100.25" + finally: + grpc_server.stop(grace=0).wait()