{"record":{"id":"3f22cb53091397f7","repo":"nautechsystems/nautilus_trader","slug":"cannot-take-ownership-other-references-exist","errorCode":null,"errorMessage":"Cannot take ownership - other references exist","messagePattern":"Cannot take ownership - other references exist","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"crates/adapters/bitmex/src/websocket/client.rs","lineNumber":644,"sourceCode":"            ))\n        })?;\n\n        Ok(())\n    }\n\n    /// Provides the internal stream as a channel-based stream.\n    ///\n    /// # Panics\n    ///\n    /// This function panics:\n    /// - If the websocket is not connected.\n    /// - If `stream` has already been called somewhere else (stream receiver is then taken).\n    pub fn stream(&mut self) -> impl Stream<Item = BitmexWsMessage> + use<> {\n        let rx = self\n            .out_rx\n            .take()\n            .expect(\"Stream receiver already taken or not connected\");\n        let mut rx = Arc::try_unwrap(rx).expect(\"Cannot take ownership - other references exist\");\n        async_stream::stream! {\n            while let Some(msg) = rx.recv().await {\n                yield msg;\n            }\n        }\n    }\n\n    /// Closes the client.\n    ///\n    /// # Errors\n    ///\n    /// Returns an error if the WebSocket is not connected or if closing fails.\n    pub async fn close(&mut self) -> Result<(), BitmexWsError> {\n        log::debug!(\"Starting close process\");\n\n        self.signal.store(true, Ordering::Relaxed);\n\n        // Send Disconnect command to handler","sourceCodeStart":626,"sourceCodeEnd":662,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/18893faf8b356be3320add8de2f861b0b647cf06/crates/adapters/bitmex/src/websocket/client.rs#L626-L662","documentation":"BitmexWebSocketClient::stream() consumes the single `Arc`-wrapped broadcast receiver (`out_rx`) by `take()`-ing it and then calling `Arc::try_unwrap`. The panic fires when other `Arc` clones still exist, meaning the receiver is shared and exclusive ownership cannot be obtained. The library requires that `stream()` be called exactly once and that no other holder of the receiver remains.","triggerScenarios":"Calling `client.stream()` while another clone of the internal `Arc<Receiver<BitmexWsMessage>>` is still alive (e.g. a previously obtained stream is still running, or a clone was taken for another task).","commonSituations":"Calling `stream()` twice on the same client; spawning two consumers on one WebSocket client; keeping a reference to the stream alive while reconnecting/re-creating the stream.","solutions":["Call `stream()` at most once per client connection and drop any previously obtained stream before calling again.","Create a fresh BitmexWebSocketClient (or reconnect) for each independent consumer instead of sharing one receiver.","If broadcast semantics to multiple consumers are needed, subscribe/broadcast upstream rather than unwrapping the single Arc.","Ensure no background task still holds a clone of the receiver when `stream()` is called."],"exampleFix":"// before\nlet s1 = client.stream();\nlet s2 = client.stream(); // panics: other references exist\n// after\nlet s1 = client.stream(); // single consumer; drop s1 before re-streaming\n// or: build a second client for the second consumer\nlet s2 = other_client.stream();","handlingStrategy":"validation","validationCode":"// Call stream() exactly once per client; track with a flag\nif stream_already_created {\n    panic!(\"stream() already called; reuse the existing stream or create a new client\");\n}","typeGuard":null,"tryCatchPattern":"// Rust panics cannot be caught except via catch_unwind; prefer\nlet stream = client.stream(); // keep the returned stream; never call stream() again\nwhile let Some(msg) = stream.next().await { /* single consumer only */ }","preventionTips":["One consumer per BitmexWebSocketClient; create a new client for additional consumers.","Never clone or share the internal receiver; use the returned stream directly.","Drop an old stream before reconnecting and re-streaming."],"tags":["rust","websocket","panic","arc-ownership"],"backgroundTag":"invalid-state-transition","analyzedSha":"18893faf8b356be3320add8de2f861b0b647cf06","analyzedAt":"2026-09-08T20:49:34.690Z","contentChangedAt":"2026-09-08T20:49:34.690Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}