-
-
Notifications
You must be signed in to change notification settings - Fork 382
refactor: move Connect, OnClose, OnOpen, OnError and OnMessage to @asyncapi/generator-components
#1717
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
refactor: move Connect, OnClose, OnOpen, OnError and OnMessage to @asyncapi/generator-components
#1717
Changes from 6 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
92ccb4b
feat: move Connect, OnClose, OnOpen, OnError and OnMessage to @asynca…
Adi-204 f00b4f5
remove python connect
Adi-204 3696118
change var name
Adi-204 5041d4a
rabbit sugg
Adi-204 b8d9ba8
refactor connect test
Adi-204 8c78baf
add java also
Adi-204 6beb131
change js-docs
Adi-204 ee1ff60
solve conflicts
Adi-204 4fc7702
Merge branch 'master' into connect
Adi-204 232be37
chore: fix ci fail
Adi-204 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| import { Text, render } from '@asyncapi/generator-react-sdk'; | ||
| import { OnOpen } from './OnOpen'; | ||
| import { OnMessage } from './OnMessage'; | ||
| import { OnError } from './OnError'; | ||
| import { OnClose } from './OnClose'; | ||
|
|
||
| /** | ||
| * @typedef {'python' | 'javascript' | 'dart'} SupportedLanguage | ||
| * Supported programming languages for WebSocket connection method generation. | ||
| */ | ||
|
|
||
| /** | ||
| * Mapping of supported programming languages to their WebSocket connection method implementations. | ||
| * | ||
| * @type {Object.<SupportedLanguage, Function>} | ||
| */ | ||
| const websocketConnectMethod = { | ||
| javascript: (onOpenMethod, onMessageMethod, onErrorMethod, onCloseMethod) => { | ||
| return { | ||
| connectMethod: `// Method to establish a WebSocket connection | ||
| connect() { | ||
| return new Promise((resolve, reject) => { | ||
| this.websocket = new WebSocket(this.url); | ||
| ${onOpenMethod} | ||
| ${onMessageMethod} | ||
| ${onErrorMethod} | ||
| ${onCloseMethod} | ||
| }); | ||
| }` | ||
| }; | ||
| }, | ||
| python: (onOpenMethod, onMessageMethod, onErrorMethod, onCloseMethod) => { | ||
| const onConnectMethod = `def connect(self): | ||
| """Establish the connection and start the run_forever loop in a background thread.""" | ||
| ssl_opts = {"ca_certs": certifi.where()} | ||
| self.ws_app = websocket.WebSocketApp( | ||
| self.url, | ||
| on_open=self.on_open, | ||
| on_message=self.on_message, | ||
| on_error=self.on_error, | ||
| on_close=self.on_close | ||
| ) | ||
| # Run the WebSocketApp's run_forever in a separate thread with multithreading enabled. | ||
| def run(): | ||
|
|
||
| retry = 0 | ||
| max_retries = 5 | ||
|
|
||
| while not self._stop_event.is_set() and retry < max_retries: | ||
| try: | ||
| retry += 1 | ||
| print("Starting WebSocket thread...") | ||
| self.ws_app.run_forever(sslopt=ssl_opts) | ||
| except Exception as e: | ||
| print(f"Exception in WebSocket thread: {e}") # Print full error details | ||
|
|
||
| thread = threading.Thread(target=run, daemon=True) | ||
| thread.start()`; | ||
| return { | ||
| connectMethod: `${onOpenMethod} | ||
| ${onMessageMethod} | ||
| ${onErrorMethod} | ||
| ${onCloseMethod} | ||
| ${onConnectMethod}` | ||
| }; | ||
| }, | ||
| dart: (onMessageMethod, onErrorMethod, onCloseMethod, title) => { | ||
| return { | ||
| connectMethod: `/// Method to establish a WebSocket connection | ||
| Future<void> connect() async { | ||
| if (_channel != null) { | ||
| print('Already connected to ${title} server'); | ||
| return; | ||
| } | ||
| try { | ||
| final wsUrl = Uri.parse(_url); | ||
| _channel = WebSocketChannel.connect(wsUrl); | ||
| print('Connected to ${title} server'); | ||
| /// Listen to the incoming message stream | ||
| _channel?.stream.listen( | ||
| ${onMessageMethod} | ||
| ${onErrorMethod} | ||
| ${onCloseMethod} | ||
| ); | ||
| } catch (error) { | ||
| print('Connection failed: $error'); | ||
| rethrow; | ||
| } | ||
| }` | ||
| }; | ||
| } | ||
| }; | ||
|
|
||
| /** | ||
| * Component that renders WebSocket connection method for the specified programming language. | ||
| * | ||
| * @param {Object} props - Component properties. | ||
| * @param {SupportedLanguage} props.language - The programming language for which to generate connection code. | ||
| * @param {string} props.title - The title of the WebSocket server. | ||
| */ | ||
| export function Connect({ language, title }) { | ||
| const onOpenMethod = render(<OnOpen language={language} title={title} />); | ||
| const onMessageMethod = render(<OnMessage language={language} />); | ||
| const onErrorMethod = render(<OnError language={language} />); | ||
| const onCloseMethod = render(<OnClose language={language} title={title} />); | ||
|
|
||
| const generateConnectCode = websocketConnectMethod[language]; | ||
|
|
||
| let connectMethod; | ||
|
|
||
| if (language === 'dart') { | ||
| const result = generateConnectCode(onMessageMethod, onErrorMethod, onCloseMethod, title); | ||
| connectMethod = result.connectMethod; | ||
| } else { | ||
| const result = generateConnectCode(onOpenMethod, onMessageMethod, onErrorMethod, onCloseMethod); | ||
| connectMethod = result.connectMethod; | ||
| } | ||
Adi-204 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return ( | ||
| <Text newLines={2} indent={2}> | ||
| {connectMethod} | ||
| </Text> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| import { Text } from '@asyncapi/generator-react-sdk'; | ||
|
|
||
| /** | ||
| * @typedef {'python' | 'javascript' | 'dart' | 'java' } SupportedLanguage | ||
| * Supported programming languages for WebSocket onClose handler generation. | ||
| */ | ||
|
|
||
| /** | ||
| * Mapping of supported programming languages to their WebSocket onClose event handler implementations. | ||
| * | ||
| * @type {Object.<SupportedLanguage, Function>} | ||
| */ | ||
| const websocketOnCloseMethod = { | ||
| javascript: (title) => { | ||
| return { | ||
| onCloseMethod: `// On connection close | ||
| this.websocket.onclose = () => { | ||
| console.log('Disconnected from ${title} server'); | ||
| };` | ||
| }; | ||
| }, | ||
Adi-204 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| python: (title) => { | ||
| return { | ||
| onCloseMethod: `def on_close(self, ws, close_status_code, close_msg): | ||
| print("Disconnected from ${title}", close_status_code, close_msg)` | ||
| }; | ||
| }, | ||
| dart: (title) => { | ||
| return { | ||
| onCloseMethod: `onDone: () { | ||
| _channel = null; | ||
| print('Disconnected from ${title} server'); | ||
| },` | ||
| }; | ||
| }, | ||
| java: { | ||
| quarkus: (title) => { | ||
| const onCloseMethod = `@OnClose | ||
| public void onClose(CloseReason reason, WebSocketClientConnection connection) { | ||
| int code = reason.getCode(); | ||
| Log.info("Websocket disconnected from ${title} with Close code: " + code); | ||
| } | ||
| }`; | ||
| return { onCloseMethod, indent: 2 }; | ||
| } | ||
| } | ||
| }; | ||
|
|
||
| const resolveCloseConfig = (language, framework = '') => { | ||
| const config = websocketOnCloseMethod[language]; | ||
| if (typeof config === 'function') { | ||
| return config; | ||
| } | ||
| if (framework && typeof config[framework] === 'function') { | ||
| return config[framework]; | ||
| } | ||
| }; | ||
|
|
||
| /** | ||
| * Component that renders WebSocket onClose event handler for the specified programming language. | ||
| * | ||
| * @param {Object} props - Component properties. | ||
| * @param {SupportedLanguage} props.language - The programming language for which to generate onClose handler code. | ||
| * @param {string} props.title - The title of the WebSocket server. | ||
| */ | ||
| export function OnClose({ language, framework = '', title }) { | ||
| let onCloseMethod = ''; | ||
| let indent = 0; | ||
|
|
||
| if (websocketOnCloseMethod[language]) { | ||
| const generateOnCloseCode = resolveCloseConfig(language, framework); | ||
| const closeResult = generateOnCloseCode(title); | ||
| onCloseMethod = closeResult.onCloseMethod; | ||
| indent = closeResult.indent ?? 0; | ||
| } | ||
Adi-204 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return ( | ||
| <Text indent={indent}> | ||
| {onCloseMethod} | ||
| </Text> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import { Text } from '@asyncapi/generator-react-sdk'; | ||
|
|
||
| /** | ||
| * @typedef {'python' | 'javascript' | 'dart'} SupportedLanguage | ||
| * Supported programming languages for WebSocket onError handler generation. | ||
| */ | ||
|
|
||
| /** | ||
| * Mapping of supported programming languages to their WebSocket onError event handler implementations. | ||
| * | ||
| * @type {Object.<SupportedLanguage, Function>} | ||
| */ | ||
| const websocketOnErrorMethod = { | ||
| javascript: () => { | ||
| return { | ||
| onErrorMethod: `// On error first call custom error handlers, then default error behavior | ||
| this.websocket.onerror = (error) => { | ||
| if (this.errorHandlers.length > 0) { | ||
| // Call custom error handlers | ||
| this.errorHandlers.forEach(handler => handler(error)); | ||
| } else { | ||
| // Default error behavior | ||
| console.error('WebSocket Error:', error); | ||
| } | ||
| reject(error); | ||
| };` | ||
| }; | ||
| }, | ||
| python: () => { | ||
| return { | ||
| onErrorMethod: `def on_error(self, ws, error): | ||
| print("WebSocket Error:", error) | ||
| self.handle_error(error)` | ||
| }; | ||
| }, | ||
| dart: () => { | ||
| return { | ||
| onErrorMethod: `onError: (error) { | ||
| if (_errorHandlers.isNotEmpty) { | ||
| for (var handler in _errorHandlers) { | ||
| handler(error); | ||
| } | ||
| } else { | ||
| print('WebSocket Error: $error'); | ||
| } | ||
| },` | ||
| }; | ||
| } | ||
| }; | ||
|
|
||
| /** | ||
| * Component that renders WebSocket onError event handler for the specified programming language. | ||
| * | ||
| * @param {Object} props - Component properties. | ||
| * @param {SupportedLanguage} props.language - The programming language for which to generate onError handler code. | ||
| */ | ||
| export function OnError({ language }) { | ||
| let onErrorMethod = ''; | ||
|
|
||
| if (websocketOnErrorMethod[language]) { | ||
| const generateErrorCode = websocketOnErrorMethod[language]; | ||
| const errorResult = generateErrorCode(); | ||
| onErrorMethod = errorResult.onErrorMethod; | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return ( | ||
| <Text> | ||
| {onErrorMethod} | ||
| </Text> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| import { Text } from '@asyncapi/generator-react-sdk'; | ||
|
|
||
| /** | ||
| * @typedef {'python' | 'javascript' | 'dart'} SupportedLanguage | ||
| * Supported programming languages for WebSocket onMessage handler generation. | ||
| */ | ||
|
|
||
| /** | ||
| * Mapping of supported programming languages to their WebSocket onMessage event handler implementations. | ||
| * | ||
| * @type {Object.<SupportedLanguage, Function>} | ||
| */ | ||
| const websocketOnMessageMethod = { | ||
| javascript: () => { | ||
| return { | ||
| onMessageMethod: `// On receiving a message | ||
| this.websocket.onmessage = (event) => { | ||
| if (this.messageHandlers.length > 0) { | ||
| // Call custom message handlers | ||
| this.messageHandlers.forEach(handler => { | ||
| if (typeof handler === 'function') { | ||
| this.handleMessage(event.data, handler); | ||
| } | ||
| }); | ||
| } else { | ||
| // Default message logging | ||
| console.log('Message received:', event.data); | ||
| } | ||
| };` | ||
| }; | ||
| }, | ||
| python: () => { | ||
| return { | ||
| onMessageMethod: `def on_message(self, ws, message): | ||
| self.handle_message(message)` | ||
| }; | ||
| }, | ||
| dart: () => { | ||
| return { | ||
| onMessageMethod: `(message) { | ||
| if (_messageHandlers.isNotEmpty) { | ||
| for (var handler in _messageHandlers) { | ||
| _handleMessage(message, handler); | ||
| } | ||
| } else { | ||
| print('Message received: $message'); | ||
| } | ||
| },` | ||
| }; | ||
| } | ||
| }; | ||
|
|
||
| /** | ||
| * Component that renders WebSocket onMessage event handler for the specified programming language. | ||
| * | ||
| * @param {Object} props - Component properties. | ||
| * @param {SupportedLanguage} props.language - The programming language for which to generate onMessage handler code. | ||
| */ | ||
| export function OnMessage({ language }) { | ||
| let onMessageMethod = ''; | ||
|
|
||
| if (websocketOnMessageMethod[language]) { | ||
| const generateOnMessageCode = websocketOnMessageMethod[language]; | ||
| const messageResult = generateOnMessageCode(); | ||
| onMessageMethod = messageResult.onMessageMethod; | ||
| } | ||
|
|
||
| return ( | ||
| <Text> | ||
| {onMessageMethod} | ||
| </Text> | ||
| ); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.