[desktop] UI fix: integrate NgZone into Tauri WebSocket connection for better change detection
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import WebSocket, { Message } from '@tauri-apps/plugin-websocket';
|
||||
import WebSocket, { ConnectionConfig, Message } from '@tauri-apps/plugin-websocket';
|
||||
import { Subject, Observable } from 'rxjs';
|
||||
import { WebSocketSubject, WebSocketSubjectConfig } from 'rxjs/webSocket';
|
||||
import { NgZone } from '@angular/core';
|
||||
|
||||
const LOG_PREFIX = '[tauri_ws]';
|
||||
|
||||
@@ -9,6 +10,7 @@ const LOG_PREFIX = '[tauri_ws]';
|
||||
*
|
||||
* @template T - The type of messages sent and received through the WebSocket.
|
||||
* @param {WebSocketSubjectConfig<T>} opts - Configuration options for the WebSocket connection.
|
||||
* @param {NgZone} ngZone - Angular's NgZone to ensure change detection runs properly.
|
||||
* @returns {WebSocketSubject<T>} - An RxJS WebSocketSubject-compatible object for interacting with the WebSocket.
|
||||
* @throws {Error} If the `serializer` or `deserializer` functions are not provided.
|
||||
*
|
||||
@@ -17,9 +19,9 @@ const LOG_PREFIX = '[tauri_ws]';
|
||||
* url: 'ws://example.com',
|
||||
* serializer: JSON.stringify,
|
||||
* deserializer: JSON.parse,
|
||||
* });
|
||||
* }, ngZone);
|
||||
*/
|
||||
export function createTauriWsConnection<T>(opts: WebSocketSubjectConfig<T>): WebSocketSubject<T> {
|
||||
export function createTauriWsConnection<T>(opts: WebSocketSubjectConfig<T>, ngZone: NgZone): WebSocketSubject<T> {
|
||||
if (!opts.serializer) throw new Error(`${LOG_PREFIX} Messages Serializer not provided!`);
|
||||
if (!opts.deserializer) throw new Error(`${LOG_PREFIX} Messages Deserializer not provided!`);
|
||||
|
||||
@@ -37,8 +39,12 @@ export function createTauriWsConnection<T>(opts: WebSocketSubjectConfig<T>): Web
|
||||
if (!descriptionToLog) return;
|
||||
if (!error) error = new Error(descriptionToLog);
|
||||
console.error(`${LOG_PREFIX} ${descriptionToLog}:`, error);
|
||||
|
||||
// Run inside NgZone to ensure Angular detects this change
|
||||
ngZone.run(() => {
|
||||
// This completes the observable and prevents further messages from being processed.
|
||||
messageSubject.error(error);
|
||||
});
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////
|
||||
@@ -68,23 +74,35 @@ export function createTauriWsConnection<T>(opts: WebSocketSubjectConfig<T>): Web
|
||||
return;
|
||||
}
|
||||
|
||||
// Run outside NgZone for better performance during send operations
|
||||
ngZone.runOutsideAngular(() => {
|
||||
try {
|
||||
wsConnection.send(serializedMessage).catch((err: Error) => {
|
||||
wsConnection!.send(serializedMessage).catch((err: Error) => {
|
||||
notifySubjectError('Error sending text message', err);
|
||||
});
|
||||
} catch (error) {
|
||||
notifySubjectError('Error sending message', error);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
complete: () => {
|
||||
if (wsConnection) {
|
||||
console.log(`${LOG_PREFIX} Closing connection`);
|
||||
opts.closingObserver?.next(undefined);
|
||||
wsConnection.disconnect().catch((err: Error) => console.error(`${LOG_PREFIX} Error closing connection:`, err));
|
||||
wsConnection = null;
|
||||
|
||||
// Run inside NgZone to ensure Angular detects this change
|
||||
ngZone.run(() => {
|
||||
if (opts.closingObserver?.next) {
|
||||
opts.closingObserver.next(undefined);
|
||||
}
|
||||
|
||||
wsConnection!.disconnect().catch((err: Error) => console.error(`${LOG_PREFIX} Error closing connection:`, err));
|
||||
wsConnection = null;
|
||||
messageSubject.complete();
|
||||
});
|
||||
} else {
|
||||
messageSubject.complete();
|
||||
}
|
||||
},
|
||||
|
||||
// RxJS Observable methods required for compatibility
|
||||
@@ -97,14 +115,17 @@ export function createTauriWsConnection<T>(opts: WebSocketSubjectConfig<T>): Web
|
||||
//////////////////////////////////////////////////////////////
|
||||
// Connect to WebSocket
|
||||
//////////////////////////////////////////////////////////////
|
||||
console.log(`${LOG_PREFIX} Connecting to WebSocket:`, opts.url);
|
||||
|
||||
const connectOptions: Record<string, any> = {};
|
||||
console.log(`${LOG_PREFIX} Connecting to WebSocket:`, opts.url, connectOptions);
|
||||
WebSocket.connect(opts.url, connectOptions)
|
||||
// Connect outside of Angular zone for better performance
|
||||
ngZone.runOutsideAngular(() => {
|
||||
WebSocket.connect(opts.url)
|
||||
.then((ws) => {
|
||||
wsConnection = ws;
|
||||
console.log(`${LOG_PREFIX} Connection established`);
|
||||
|
||||
// Run inside NgZone to ensure Angular detects this connection event
|
||||
ngZone.run(() => {
|
||||
// Create a mock Event for the openObserver
|
||||
if (opts.openObserver) {
|
||||
const mockEvent = new Event('open') as Event;
|
||||
@@ -116,11 +137,13 @@ export function createTauriWsConnection<T>(opts: WebSocketSubjectConfig<T>): Web
|
||||
const message = pendingMessages.shift();
|
||||
if (message) webSocketSubject.next(message);
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
// Add a single listener for ALL message types according to Tauri WebSocket API
|
||||
// The addListener method takes a single callback function that receives messages
|
||||
ws.addListener((message: Message) => {
|
||||
// Process message inside ngZone to trigger change detection
|
||||
ngZone.run(() => {
|
||||
try {
|
||||
// Handle different message types from Tauri
|
||||
switch (message.type) {
|
||||
@@ -180,6 +203,7 @@ export function createTauriWsConnection<T>(opts: WebSocketSubjectConfig<T>): Web
|
||||
// Don't error the subject on message processing errors to keep connection alive
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
console.log(`${LOG_PREFIX} Listener added successfully`);
|
||||
|
||||
@@ -190,6 +214,7 @@ export function createTauriWsConnection<T>(opts: WebSocketSubjectConfig<T>): Web
|
||||
.catch((error: Error) => {
|
||||
notifySubjectError('Connection failed', error);
|
||||
});
|
||||
});
|
||||
|
||||
// Cast to WebSocketSubject<T>
|
||||
return webSocketSubject as unknown as WebSocketSubject<T>;
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Injectable, NgZone } from '@angular/core';
|
||||
import { webSocket, WebSocketSubject, WebSocketSubjectConfig } from 'rxjs/webSocket';
|
||||
import { createTauriWsConnection } from './platform-specific/tauri/tauri-websocket-subject';
|
||||
import { IsTauriEnvironment } from './platform-specific/utils';
|
||||
|
||||
@Injectable()
|
||||
export class WebsocketService {
|
||||
constructor() { }
|
||||
constructor(private ngZone: NgZone) { }
|
||||
|
||||
/**
|
||||
* createConnection creates a new websocket connection using opts.
|
||||
@@ -15,7 +15,7 @@ export class WebsocketService {
|
||||
createConnection<T>(opts: WebSocketSubjectConfig<T>): WebSocketSubject<T> {
|
||||
if (IsTauriEnvironment()) {
|
||||
console.log('[portmaster-api] Running under Tauri - Using Tauri WebSocket');
|
||||
return createTauriWsConnection<T>(opts);
|
||||
return createTauriWsConnection<T>(opts, this.ngZone);
|
||||
}
|
||||
|
||||
console.log('[portmaster-api] Running in browser - Using RxJS WebSocket');
|
||||
|
||||
Reference in New Issue
Block a user