Compare commits

...

5 Commits

Author SHA1 Message Date
d75486ac6e v4.0.0
Some checks failed
Default (tags) / security (push) Failing after 19s
Default (tags) / test (push) Failing after 13s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-04 07:59:44 +00:00
0499db71b8 BREAKING CHANGE(socketconnection): Stricter typings, smartserve hooks, connection fixes, and tag API change 2025-12-04 07:59:44 +00:00
5b21955e04 v3.0.0
Some checks failed
Default (tags) / security (push) Failing after 17s
Default (tags) / test (push) Failing after 13s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2025-12-03 09:22:44 +00:00
09dbb00179 BREAKING CHANGE(smartsocket): Replace setExternalServer with hooks-based SmartServe integration and refactor SocketServer to support standalone and hooks modes 2025-12-03 09:22:44 +00:00
1d62c9c695 Refactor smartsocket implementation for improved WebSocket handling and message protocol
- Updated test files to use new testing library and reduced test cycles for efficiency.
- Removed dependency on smartexpress and integrated direct WebSocket handling.
- Enhanced Smartsocket and SmartsocketClient classes to support new message types and authentication flow.
- Implemented a new message interface for structured communication between client and server.
- Added external server support for smartserve with appropriate WebSocket hooks.
- Improved connection management and error handling in SocketConnection and SocketRequest classes.
- Cleaned up code and removed deprecated socket.io references in favor of native WebSocket.
2025-12-03 02:20:38 +00:00
17 changed files with 4214 additions and 5159 deletions

View File

@@ -1,5 +1,26 @@
# Changelog # Changelog
## 2025-12-04 - 4.0.0 - BREAKING CHANGE(socketconnection)
Stricter typings, smartserve hooks, connection fixes, and tag API change
- Add unified WebSocket types and adapter interface (TWebSocket, TMessageEvent, IWebSocketLike) for browser/Node and smartserve peers
- Expose smartserve integration via getSmartserveWebSocketHooks() and adapt smartserve peers to a WebSocket-like interface (readyState getter, message/close/error dispatch)
- Improve SmartsocketClient connection logic: prevent duplicate connect attempts with isConnecting flag, ensure flags are cleared on success/failure, and tighten timeout/reconnect behavior
- Improve message parsing logging to surface JSON parse errors during authentication and normal operation
- Tighten TypeScript message and payload types (use unknown instead of any, Record<string, unknown> for tag payloads)
- SocketConnection API change: getTagById() and removeTagById() are now synchronous (no longer return Promises) — this is a breaking API change
- SocketRequest: log errors when function invocation fails and ensure pending requests are removed on errors
- Bump dependency @push.rocks/smartserve to ^1.1.2 and update README to reflect SmartServe integration changes
## 2025-12-03 - 3.0.0 - BREAKING CHANGE(smartsocket)
Replace setExternalServer with hooks-based SmartServe integration and refactor SocketServer to support standalone and hooks modes
- Remove setExternalServer API and add getSmartserveWebSocketHooks on Smartsocket to provide SmartServe-compatible websocket hooks.
- SocketServer.start now becomes a no-op when no port is provided (hooks mode). When a port is set, it starts a standalone HTTP + ws server as before.
- Introduce an adapter (createWsLikeFromPeer) to adapt SmartServe peers to a WebSocket-like interface and route onMessage/onClose/onError via the adapter.
- Dispatch smartserve messages through the adapter: text/binary handling for onMessage, and dispatchClose/dispatchError for close/error events.
- Update tests: add smartserve integration test (test.smartserve.ts), adjust tagging test cleanup to stop client and delay before exit, remove outdated expressserver test.
## 2025-03-10 - 2.1.0 - feat(SmartsocketClient) ## 2025-03-10 - 2.1.0 - feat(SmartsocketClient)
Improve client reconnection logic with exponential backoff and jitter; update socket.io and @types/node dependencies Improve client reconnection logic with exponential backoff and jitter; update socket.io and @types/node dependencies

View File

@@ -1,12 +1,12 @@
{ {
"name": "@push.rocks/smartsocket", "name": "@push.rocks/smartsocket",
"version": "2.1.0", "version": "4.0.0",
"description": "Provides easy and secure websocket communication mechanisms, including server and client implementation, function call routing, connection management, and tagging.", "description": "Provides easy and secure websocket communication mechanisms, including server and client implementation, function call routing, connection management, and tagging.",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/index.d.ts",
"type": "module", "type": "module",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(tstest test/ --verbose)",
"build": "(tsbuild --web --allowimplicitany && tsbundle --from ./ts/index.ts --to dist_bundle/bundle.js)", "build": "(tsbuild --web --allowimplicitany && tsbundle --from ./ts/index.ts --to dist_bundle/bundle.js)",
"buildDocs": "tsdoc" "buildDocs": "tsdoc"
}, },
@@ -14,36 +14,34 @@
"type": "git", "type": "git",
"url": "https://code.foss.global/push.rocks/smartsocket.git" "url": "https://code.foss.global/push.rocks/smartsocket.git"
}, },
"author": "Lossless GmbH", "author": "Task Venture Capital GmbH",
"license": "MIT", "license": "MIT",
"bugs": { "bugs": {
"url": "https://gitlab.com/pushrocks/smartsocket/issues" "url": "https://community.foss.global/"
}, },
"homepage": "https://code.foss.global/push.rocks/smartsocket", "homepage": "https://code.foss.global/push.rocks/smartsocket",
"dependencies": { "dependencies": {
"@api.global/typedrequest-interfaces": "^3.0.18", "@api.global/typedrequest-interfaces": "^3.0.19",
"@api.global/typedserver": "^3.0.27", "@push.rocks/isohash": "^2.0.1",
"@push.rocks/isohash": "^2.0.0",
"@push.rocks/isounique": "^1.0.5", "@push.rocks/isounique": "^1.0.5",
"@push.rocks/lik": "^6.0.14", "@push.rocks/lik": "^6.2.2",
"@push.rocks/smartdelay": "^3.0.5", "@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartenv": "^5.0.12", "@push.rocks/smartenv": "^6.0.0",
"@push.rocks/smartjson": "^5.0.19", "@push.rocks/smartjson": "^5.2.0",
"@push.rocks/smartlog": "^3.0.3", "@push.rocks/smartlog": "^3.1.10",
"@push.rocks/smartpromise": "^4.0.3", "@push.rocks/smartpromise": "^4.2.3",
"@push.rocks/smartrx": "^3.0.7", "@push.rocks/smartrx": "^3.0.10",
"@push.rocks/smarttime": "^4.0.6", "@push.rocks/smarttime": "^4.1.1",
"engine.io": "6.6.4", "ws": "^8.18.3"
"socket.io": "4.8.1",
"socket.io-client": "4.8.1"
}, },
"devDependencies": { "devDependencies": {
"@git.zone/tsbuild": "^2.1.66", "@git.zone/tsbuild": "^3.1.2",
"@git.zone/tsbundle": "^2.0.8", "@git.zone/tsbundle": "^2.6.3",
"@git.zone/tsrun": "^1.2.44", "@git.zone/tsrun": "^2.0.0",
"@git.zone/tstest": "^1.0.77", "@git.zone/tstest": "^3.1.3",
"@push.rocks/tapbundle": "^5.0.23", "@push.rocks/smartserve": "^1.1.2",
"@types/node": "^22.13.10" "@types/node": "^24.10.1",
"@types/ws": "^8.18.1"
}, },
"private": false, "private": false,
"files": [ "files": [
@@ -66,11 +64,12 @@
"communication", "communication",
"server", "server",
"client", "client",
"socket.io", "native websocket",
"authentication", "authentication",
"reconnection", "reconnection",
"tagging", "tagging",
"function routing", "function routing",
"secure" "secure",
"rpc"
] ]
} }

7819
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

296
readme.md
View File

@@ -1,149 +1,295 @@
# @push.rocks/smartsocket # @push.rocks/smartsocket
easy and secure websocket communication
Easy and secure WebSocket communication with native WebSocket support 🔌
## Features
- 🚀 **Native WebSocket** - Uses native WebSocket API (browser) and `ws` library (Node.js)
- 🔄 **Auto Reconnection** - Exponential backoff with configurable retry limits
- 📡 **RPC-style Function Calls** - Define and call functions across server/client
- 🏷️ **Connection Tagging** - Tag connections for easy identification and routing
- 🔗 **Smartserve Integration** - Works seamlessly with `@push.rocks/smartserve`
- 🔒 **Secure Communication** - WSS support for encrypted connections
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Install ## Install
To install @push.rocks/smartsocket, you can use npm or yarn as follows:
```shell ```shell
npm install @push.rocks/smartsocket --save npm install @push.rocks/smartsocket --save
``` ```
or
or with pnpm:
```shell ```shell
yarn add @push.rocks/smartsocket pnpm add @push.rocks/smartsocket
``` ```
## Usage ## Usage
@push.rocks/smartsocket offers a robust solution for easy and secure WebSocket communication, utilizing Typescript for clean and maintainable code. Below are comprehensive examples covering various scenarios and features provided by the module. ### Quick Start - Server
### Getting Started
First, ensure you've installed the module as shown in the "Install" section. Once installed, you can start using @push.rocks/smartsocket in your project.
### Setting Up a WebSocket Server
To create a WebSocket server that clients can connect to:
```typescript ```typescript
import { Smartsocket } from '@push.rocks/smartsocket'; import { Smartsocket, SocketFunction } from '@push.rocks/smartsocket';
// Create a new instance of Smartsocket for the server. // Create server
const server = new Smartsocket({ alias: 'myServer' }); const server = new Smartsocket({
alias: 'myServer',
port: 3000
});
// Define a SocketFunction that clients can call // Define a function that clients can call
server.addSocketFunction({ const greetFunction = new SocketFunction({
funcName: 'greet', funcName: 'greet',
funcDef: async (data) => { funcDef: async (data, socketConnection) => {
console.log(`Server received: ${data.message}`); console.log(`Received greeting from ${data.name}`);
return { reply: `Hello, ${data.name}!` }; return { message: `Hello, ${data.name}!` };
} }
}); });
// Start the Smartsocket server server.addSocketFunction(greetFunction);
server.start().then(() => {
console.log('WebSocket server is running...'); // Start the server
}); await server.start();
console.log('WebSocket server running on port 3000');
``` ```
### Creating a WebSocket Client ### Quick Start - Client
Create a client that connects to the WebSocket server and interacts with it:
```typescript ```typescript
import { SmartsocketClient } from '@push.rocks/smartsocket'; import { SmartsocketClient } from '@push.rocks/smartsocket';
// Create a SmartsocketClient instance and connect to the server // Create client
const client = new SmartsocketClient({ const client = new SmartsocketClient({
url: 'ws://localhost', url: 'http://localhost',
port: 3000, port: 3000,
alias: 'myClient' alias: 'myClient',
autoReconnect: true
}); });
client.connect().then(() => { // Connect to server
console.log('Connected to WebSocket server'); await client.connect();
});
// Define a function to call the server's 'greet' function // Call server function
async function greetServer(name) { const response = await client.serverCall('greet', { name: 'Alice' });
const response = await client.serverCall('greet', { name: name, message: 'Hello!' }); console.log(response.message); // "Hello, Alice!"
console.log(`Server replied: ${response.reply}`);
}
// Use the function
greetServer('Alice');
``` ```
### Handling Disconnections and Reconnections ### Connection Options
@push.rocks/smartsocket provides mechanisms to handle client disconnections and attempt reconnections: The `SmartsocketClient` supports several configuration options:
```typescript ```typescript
client.on('disconnect', () => { const client = new SmartsocketClient({
console.log('Disconnected from server. Attempting to reconnect...'); url: 'http://localhost', // Server URL (http/https)
client.connect(); port: 3000, // Server port
alias: 'myClient', // Client identifier
autoReconnect: true, // Auto-reconnect on disconnect
maxRetries: 100, // Max reconnection attempts (default: 100)
initialBackoffDelay: 1000, // Initial backoff in ms (default: 1000)
maxBackoffDelay: 60000 // Max backoff in ms (default: 60000)
}); });
``` ```
### Sending Binary Data ### Two-Way Function Calls
The library supports the transmission of binary data efficiently: Both server and client can define and call functions on each other:
```typescript ```typescript
import fs from 'fs'; // Server calling client
const clientFunction = new SocketFunction({
funcName: 'clientTask',
funcDef: async (data) => {
return { result: 'Task completed' };
}
});
// Function to send a binary file to the server // On client
async function sendBinaryData(filePath) { client.addSocketFunction(clientFunction);
const fileBuffer = fs.readFileSync(filePath);
await client.serverCall('sendFile', { file: fileBuffer });
}
sendBinaryData('./path/to/your/file.png'); // On server - call the client
const socketConnection = server.socketConnections.findSync(conn => conn.alias === 'myClient');
const result = await server.clientCall('clientTask', { task: 'doSomething' }, socketConnection);
``` ```
### Securing Your WebSocket Communication ### Connection Tagging
@push.rocks/smartsocket leverages secure WebSocket (WSS) connections to ensure that data transferred between the client and server is encrypted. When setting up your Smartsocket server or client, use `wss://` in your URL to enable secure communication. Tag connections to identify and group them:
### Advanced Usage ```typescript
// On client
await client.addTag({
id: 'role',
payload: 'admin'
});
#### Mesh Networking // On server - find tagged connections
const adminConnections = server.socketConnections.getArray().filter(async conn => {
const tag = await conn.getTagById('role');
return tag?.payload === 'admin';
});
@push.rocks/smartsocket allows for the creation of complex mesh network configurations, enabling servers to communicate with other servers, forming a robust network with multiple nodes. // Server can also tag connections
await socketConnection.addTag({
id: 'verified',
payload: true
});
```
#### Scaling with @push.rocks/smartsocket ### Integration with Smartserve
To scale your WebSocket services, you can utilize load balancers and ensure your @push.rocks/smartsocket instances are stateless to allow for horizontal scaling. Use smartsocket with `@push.rocks/smartserve` for advanced HTTP/WebSocket handling:
### Conclusion ```typescript
import { SmartServe } from '@push.rocks/smartserve';
import { Smartsocket } from '@push.rocks/smartsocket';
This guide has covered how to set up basic WebSocket communication with @push.rocks/smartsocket, handle disconnections/reconnections, secure your communication, send binary data, and briefly touched on advanced concepts like mesh networking and scaling. // Create smartsocket without a port (hooks mode)
const smartsocket = new Smartsocket({ alias: 'myServer' });
For more detailed documentation, visit [the official @push.rocks/smartsocket GitLab repository](https://gitlab.com/pushrocks/smartsocket). // Get WebSocket hooks and pass them to SmartServe
const wsHooks = smartsocket.getSmartserveWebSocketHooks();
const smartserve = new SmartServe({
port: 3000,
websocket: wsHooks
});
Remember, WebSocket communication with @push.rocks/smartsocket is not only about sending and receiving messages. It's about creating a fast, reliable, and secure communication channel for your real-time applications. // Add socket functions as usual
smartsocket.addSocketFunction(myFunction);
Happy coding! // Start smartserve (smartsocket hooks mode doesn't need start())
await smartserve.start();
```
--- ### Handling Disconnections
Please note, the documentation above is a starting point. Depending on the complexity and requirements of your application, you may need to explore more features and configurations provided by @push.rocks/smartsocket. Always refer to the official documentation for the most current information and best practices. The client automatically handles reconnection with exponential backoff:
```typescript
const client = new SmartsocketClient({
url: 'http://localhost',
port: 3000,
alias: 'myClient',
autoReconnect: true,
maxRetries: 10,
initialBackoffDelay: 500,
maxBackoffDelay: 5000
});
// Listen for connection status changes
client.eventSubject.subscribe(status => {
console.log('Connection status:', status);
// Status can be: 'new', 'connecting', 'connected', 'disconnecting', 'timedOut'
});
await client.connect();
// Manually disconnect without auto-reconnect
await client.disconnect();
// Stop the client completely (disables auto-reconnect)
await client.stop();
```
### Secure Connections (WSS)
For secure WebSocket connections, use HTTPS URLs:
```typescript
const client = new SmartsocketClient({
url: 'https://secure.example.com', // HTTPS triggers WSS
port: 443,
alias: 'secureClient'
});
```
### TypedRequest Integration
For strongly-typed RPC calls, define interfaces:
```typescript
interface IGreetRequest {
method: 'greet';
request: { name: string };
response: { message: string };
}
// Type-safe server call
const response = await client.serverCall<IGreetRequest>('greet', { name: 'Bob' });
// response is typed as { message: string }
```
## API Reference
### Smartsocket (Server)
| Method | Description |
|--------|-------------|
| `start()` | Start the WebSocket server (not needed in hooks mode) |
| `stop()` | Stop the server and close all connections |
| `addSocketFunction(fn)` | Register a function that clients can call |
| `clientCall(funcName, data, connection)` | Call a function on a specific client |
| `getSmartserveWebSocketHooks()` | Get hooks for smartserve integration |
### SmartsocketClient
| Method | Description |
|--------|-------------|
| `connect()` | Connect to the server |
| `disconnect()` | Disconnect from the server |
| `stop()` | Disconnect and disable auto-reconnect |
| `serverCall(funcName, data)` | Call a function on the server |
| `addSocketFunction(fn)` | Register a function the server can call |
| `addTag(tag)` | Add a tag to the connection |
| `getTagById(id)` | Get a tag by its ID |
| `removeTagById(id)` | Remove a tag by its ID |
### SocketFunction
```typescript
const fn = new SocketFunction({
funcName: 'myFunction',
funcDef: async (data, socketConnection) => {
// data: the request payload
// socketConnection: the calling connection
return { result: 'response' };
}
});
```
## Architecture
```
┌─────────────────┐ WebSocket ┌─────────────────┐
│ SmartsocketClient │◄────────────────────────►│ Smartsocket │
│ (Browser/Node) │ Native WebSocket │ (Server) │
└─────────────────┘ └─────────────────┘
│ │
│ SocketFunction SocketFunction │
│ (serverCall) (clientCall) │
│ │
└──────────────── RPC-style Calls ──────────────┘
```
## License and Legal Information ## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. **Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks ### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH. This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information ### Company Information
Task Venture Capital GmbH Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc. For any legal inquiries or further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works. By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

View File

@@ -1,103 +0,0 @@
// tslint:disable-next-line:no-implicit-dependencies
import { expect, expectAsync, tap } from '@push.rocks/tapbundle';
import * as isohash from '@push.rocks/isohash';
import * as smartexpress from '@api.global/typedserver';
import * as smartsocket from '../ts/index.js';
let testSmartsocket: smartsocket.Smartsocket;
let testSmartsocketClient: smartsocket.SmartsocketClient;
let testSocketFunction1: smartsocket.SocketFunction<any>;
let myseServer: smartexpress.servertools.Server;
const testConfig = {
port: 3000,
};
// class smartsocket
tap.test('should create a new smartsocket', async () => {
testSmartsocket = new smartsocket.Smartsocket({ alias: 'testserver', port: testConfig.port });
expect(testSmartsocket).toBeInstanceOf(smartsocket.Smartsocket);
});
tap.test('Should accept an smartExpressServer as server', async () => {
myseServer = new smartexpress.servertools.Server({
cors: true,
forceSsl: false,
port: testConfig.port,
});
testSmartsocket.setExternalServer('smartexpress', myseServer);
await myseServer.start();
});
// class SocketFunction
tap.test('should register a new Function', async () => {
testSocketFunction1 = new smartsocket.SocketFunction({
funcDef: async (dataArg, socketConnectionArg) => {
return dataArg;
},
funcName: 'testFunction1',
});
testSmartsocket.addSocketFunction(testSocketFunction1);
console.log(testSmartsocket.socketFunctions);
});
tap.test('should start listening when .started is called', async () => {
await testSmartsocket.start();
});
// class SmartsocketClient
tap.test('should react to a new websocket connection from client', async () => {
testSmartsocketClient = new smartsocket.SmartsocketClient({
port: testConfig.port,
url: 'http://localhost',
alias: 'testClient1',
});
testSmartsocketClient.addSocketFunction(testSocketFunction1);
await testSmartsocketClient.connect();
});
tap.test('client should disconnect and reconnect', async (tools) => {
await testSmartsocketClient.disconnect();
await tools.delayFor(100);
await testSmartsocketClient.connect();
});
tap.test('2 clients should connect in parallel', async () => {
// TODO: implement parallel test
});
tap.test('should be able to make a functionCall from client to server', async () => {
const totalCycles = 20000;
let counter = 0;
let startTime = Date.now();
while (counter < totalCycles) {
const randomString = `hello ${Math.random()}`;
const response: any = await testSmartsocketClient.serverCall('testFunction1', {
value1: randomString,
});
expect(response.value1).toEqual(randomString);
if (counter % 100 === 0) {
console.log(
`processed 100 more messages in ${Date.now() - startTime}ms. ${
totalCycles - counter
} messages to go.`
);
startTime = Date.now();
}
counter++;
}
});
tap.test('should be able to make a functionCall from server to client', async () => {});
// terminate
tap.test('should close the server', async () => {
await testSmartsocket.stop();
await myseServer.stop();
});
tap.start();

View File

@@ -1,5 +1,4 @@
// tslint:disable-next-line:no-implicit-dependencies import { expect, tap } from '@git.zone/tstest/tapbundle';
import { expect, tap } from '@push.rocks/tapbundle';
import * as smartsocket from '../ts/index.js'; import * as smartsocket from '../ts/index.js';
@@ -64,6 +63,9 @@ tap.test('should react to a new websocket connection from client', async () => {
url: 'http://localhost', url: 'http://localhost',
alias: 'testClient1', alias: 'testClient1',
autoReconnect: true, autoReconnect: true,
maxRetries: 20,
initialBackoffDelay: 500,
maxBackoffDelay: 3000,
}); });
testSmartsocketClient.addSocketFunction(testSocketFunctionClient); testSmartsocketClient.addSocketFunction(testSocketFunctionClient);
await testSmartsocketClient.connect(); await testSmartsocketClient.connect();
@@ -129,7 +131,8 @@ tap.test('should be able to switch to a new server', async (toolsArg) => {
await testSmartsocket.stop(); await testSmartsocket.stop();
testSmartsocket = new smartsocket.Smartsocket({ alias: 'testserver2', port: testConfig.port }); testSmartsocket = new smartsocket.Smartsocket({ alias: 'testserver2', port: testConfig.port });
await testSmartsocket.start(); await testSmartsocket.start();
await toolsArg.delayFor(30000); // Wait for client to reconnect with shorter backoff settings
await toolsArg.delayFor(5000);
}); });
tap.test('should be able to locate a connection tag after reconnect', async (tools) => { tap.test('should be able to locate a connection tag after reconnect', async (tools) => {
@@ -149,4 +152,4 @@ tap.test('should close the server', async (tools) => {
tools.delayFor(1000).then(() => process.exit(0)); tools.delayFor(1000).then(() => process.exit(0));
}); });
tap.start(); export default tap.start();

91
test/test.smartserve.ts Normal file
View File

@@ -0,0 +1,91 @@
import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as smartsocket from '../ts/index.js';
import { SmartServe } from '@push.rocks/smartserve';
let smartserveInstance: SmartServe;
let testSmartsocket: smartsocket.Smartsocket;
let testSmartsocketClient: smartsocket.SmartsocketClient;
let testSocketFunction: smartsocket.SocketFunction<any>;
const testConfig = {
port: 3000,
};
// Setup smartsocket with smartserve integration
tap.test('should create smartsocket and smartserve with websocket hooks', async () => {
// Create smartsocket (no port - hooks mode for smartserve integration)
testSmartsocket = new smartsocket.Smartsocket({ alias: 'testserver-smartserve' });
expect(testSmartsocket).toBeInstanceOf(smartsocket.Smartsocket);
// Get websocket hooks from smartsocket and pass to smartserve
const wsHooks = testSmartsocket.getSmartserveWebSocketHooks();
smartserveInstance = new SmartServe({
port: testConfig.port,
websocket: wsHooks,
});
// That's it! No setExternalServer needed - hooks connect everything
});
tap.test('should register a socket function', async () => {
testSocketFunction = new smartsocket.SocketFunction({
funcDef: async (dataArg, socketConnectionArg) => {
return dataArg;
},
funcName: 'testFunction1',
});
testSmartsocket.addSocketFunction(testSocketFunction);
});
tap.test('should start smartserve', async () => {
await smartserveInstance.start();
// No need to call testSmartsocket.start() - hooks mode doesn't need it
});
tap.test('should connect client through smartserve', async () => {
testSmartsocketClient = new smartsocket.SmartsocketClient({
port: testConfig.port,
url: 'http://localhost',
alias: 'testClient1',
});
testSmartsocketClient.addSocketFunction(testSocketFunction);
await testSmartsocketClient.connect();
});
tap.test('should be able to make a functionCall from client to server', async () => {
const response: any = await testSmartsocketClient.serverCall('testFunction1', {
value1: 'hello from smartserve test',
});
expect(response.value1).toEqual('hello from smartserve test');
});
tap.test('should be able to make multiple function calls', async () => {
for (let i = 0; i < 10; i++) {
const randomString = `message-${i}-${Math.random()}`;
const response: any = await testSmartsocketClient.serverCall('testFunction1', {
value1: randomString,
});
expect(response.value1).toEqual(randomString);
}
});
tap.test('client should disconnect and reconnect through smartserve', async (tools) => {
await testSmartsocketClient.disconnect();
await tools.delayFor(100);
await testSmartsocketClient.connect();
// Verify connection still works after reconnect
const response: any = await testSmartsocketClient.serverCall('testFunction1', {
value1: 'after reconnect',
});
expect(response.value1).toEqual('after reconnect');
});
// Cleanup
tap.test('should close the server', async (tools) => {
await testSmartsocketClient.stop();
await testSmartsocket.stop();
await smartserveInstance.stop();
tools.delayFor(1000).then(() => process.exit(0));
});
export default tap.start();

View File

@@ -1,5 +1,4 @@
// tslint:disable-next-line:no-implicit-dependencies import { expect, tap } from '@git.zone/tstest/tapbundle';
import { expect, tap } from '@push.rocks/tapbundle';
import * as smartsocket from '../ts/index.js'; import * as smartsocket from '../ts/index.js';
@@ -140,8 +139,10 @@ tap.test('should be able to locate a connection tag after reconnect', async (too
}); });
// terminate // terminate
tap.test('should close the server', async () => { tap.test('should close the server', async (tools) => {
await testSmartsocketClient.stop();
await testSmartsocket.stop(); await testSmartsocket.stop();
tools.delayFor(1000).then(() => process.exit(0));
}); });
tap.start(); export default tap.start();

View File

@@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartsocket', name: '@push.rocks/smartsocket',
version: '2.1.0', version: '4.0.0',
description: 'Provides easy and secure websocket communication mechanisms, including server and client implementation, function call routing, connection management, and tagging.' description: 'Provides easy and secure websocket communication mechanisms, including server and client implementation, function call routing, connection management, and tagging.'
} }

View File

@@ -1,2 +1,3 @@
export * from './connection.js'; export * from './connection.js';
export * from './tag.js'; export * from './tag.js';
export * from './message.js';

67
ts/interfaces/message.ts Normal file
View File

@@ -0,0 +1,67 @@
/**
* Message types for the smartsocket protocol
*/
export type TMessageType =
| 'authRequest' // Server requests authentication from client
| 'auth' // Client provides authentication data
| 'authResponse' // Server responds to authentication
| 'serverReady' // Server signals it's fully ready
| 'function' // Function call request
| 'functionResponse' // Function call response
| 'tagUpdate'; // Tag store synchronization
/**
* Base message interface for all smartsocket messages
*/
export interface ISocketMessage<T = unknown> {
type: TMessageType;
id?: string; // For request/response correlation
payload: T;
}
/**
* Authentication request payload (server -> client)
*/
export interface IAuthRequestPayload {
serverAlias: string;
}
/**
* Authentication data payload (client -> server)
*/
export interface IAuthPayload {
alias: string;
}
/**
* Authentication response payload (server -> client)
*/
export interface IAuthResponsePayload {
success: boolean;
error?: string;
}
/**
* Function call payload
*/
export interface IFunctionCallPayload<T = unknown> {
funcName: string;
funcData: T;
}
/**
* Tag update payload
*/
export interface ITagUpdatePayload {
tags: Record<string, unknown>;
}
/**
* Helper type for creating typed messages
*/
export type TAuthRequestMessage = ISocketMessage<IAuthRequestPayload>;
export type TAuthMessage = ISocketMessage<IAuthPayload>;
export type TAuthResponseMessage = ISocketMessage<IAuthResponsePayload>;
export type TFunctionMessage = ISocketMessage<IFunctionCallPayload>;
export type TFunctionResponseMessage = ISocketMessage<IFunctionCallPayload>;
export type TTagUpdateMessage = ISocketMessage<ITagUpdatePayload>;

View File

@@ -26,7 +26,6 @@ export class Smartsocket {
public alias: string; public alias: string;
public smartenv = new plugins.smartenv.Smartenv(); public smartenv = new plugins.smartenv.Smartenv();
public options: ISmartsocketConstructorOptions; public options: ISmartsocketConstructorOptions;
public io: pluginsTyped.socketIo.Server;
public socketConnections = new plugins.lik.ObjectMap<SocketConnection>(); public socketConnections = new plugins.lik.ObjectMap<SocketConnection>();
public socketFunctions = new plugins.lik.ObjectMap<SocketFunction<any>>(); public socketFunctions = new plugins.lik.ObjectMap<SocketFunction<any>>();
public socketRequests = new plugins.lik.ObjectMap<SocketRequest<any>>(); public socketRequests = new plugins.lik.ObjectMap<SocketRequest<any>>();
@@ -40,26 +39,59 @@ export class Smartsocket {
this.alias = plugins.isounique.uni(this.options.alias); this.alias = plugins.isounique.uni(this.options.alias);
} }
public async setExternalServer(serverType: 'smartexpress', serverArg: any) { /**
await this.socketServer.setExternalServer(serverType, serverArg); * Returns WebSocket hooks for integration with smartserve
* Pass these hooks to SmartServe's websocket config
*/
public getSmartserveWebSocketHooks(): pluginsTyped.ISmartserveWebSocketHooks {
return this.socketServer.getSmartserveWebSocketHooks();
} }
/** /**
* starts smartsocket * starts smartsocket
*/ */
public async start() { public async start() {
const socketIoModule = await this.smartenv.getSafeNodeModule('socket.io');
this.io = new socketIoModule.Server(await this.socketServer.getServerForSocketIo(), {
cors: {
allowedHeaders: '*',
methods: '*',
origin: '*',
},
});
await this.socketServer.start(); await this.socketServer.start();
this.io.on('connection', (socketArg) => { }
this._handleSocketConnection(socketArg);
/**
* Handle a new WebSocket connection
* Called by SocketServer when a new connection is established
*/
public async handleNewConnection(socket: pluginsTyped.TWebSocket | pluginsTyped.IWebSocketLike) {
const socketConnection: SocketConnection = new SocketConnection({
alias: undefined,
authenticated: false,
side: 'server',
smartsocketHost: this,
socket: socket,
}); });
logger.log('info', 'Socket connected. Trying to authenticate...');
this.socketConnections.add(socketConnection);
// Handle disconnection
const handleClose = () => {
this.socketConnections.remove(socketConnection);
socketConnection.eventSubject.next('disconnected');
};
(socket as pluginsTyped.IWebSocketLike).addEventListener('close', handleClose);
(socket as pluginsTyped.IWebSocketLike).addEventListener('error', handleClose);
try {
await socketConnection.authenticate();
await socketConnection.listenToFunctionRequests();
// Signal that the server is ready
socketConnection.sendMessage({
type: 'serverReady',
payload: {},
});
} catch (err) {
logger.log('warn', `Authentication failed: ${err}`);
this.socketConnections.remove(socketConnection);
}
} }
/** /**
@@ -77,10 +109,9 @@ export class Smartsocket {
} }
}); });
this.socketConnections.wipe(); this.socketConnections.wipe();
this.io.close();
// stop the corresponging server // stop the corresponding server
this.socketServer.stop(); await this.socketServer.stop();
} }
// communication // communication
@@ -110,28 +141,4 @@ export class Smartsocket {
public addSocketFunction(socketFunction: SocketFunction<any>) { public addSocketFunction(socketFunction: SocketFunction<any>) {
this.socketFunctions.add(socketFunction); this.socketFunctions.add(socketFunction);
} }
/**
* the standard handler for new socket connections
*/
private async _handleSocketConnection(socketArg: pluginsTyped.socketIo.Socket) {
const socketConnection: SocketConnection = new SocketConnection({
alias: undefined,
authenticated: false,
side: 'server',
smartsocketHost: this,
socket: socketArg,
});
logger.log('info', 'Socket connected. Trying to authenticate...');
this.socketConnections.add(socketConnection);
const disconnectSubscription = socketConnection.eventSubject.subscribe((eventArg) => {
if (eventArg === 'disconnected') {
this.socketConnections.remove(socketConnection);
disconnectSubscription.unsubscribe();
}
});
await socketConnection.authenticate();
await socketConnection.listenToFunctionRequests();
await socketConnection.socket.emit('serverFullyReactive');
}
} }

View File

@@ -16,7 +16,7 @@ import { logger } from './smartsocket.logging.js';
export interface ISmartsocketClientOptions { export interface ISmartsocketClientOptions {
port: number; port: number;
url: string; url: string;
alias: string; // an alias makes it easier to identify this client in a multo client environment alias: string; // an alias makes it easier to identify this client in a multi client environment
autoReconnect?: boolean; autoReconnect?: boolean;
maxRetries?: number; // maximum number of reconnection attempts maxRetries?: number; // maximum number of reconnection attempts
initialBackoffDelay?: number; // initial backoff delay in ms initialBackoffDelay?: number; // initial backoff delay in ms
@@ -97,67 +97,114 @@ export class SmartsocketClient {
this.socketFunctions.add(socketFunction); this.socketFunctions.add(socketFunction);
} }
private isReconnecting = false;
private isConnecting = false;
/** /**
* connect the client to the server * connect the client to the server
*/ */
public async connect() { public async connect() {
// Reset retry counters on new connection attempt // Prevent duplicate connection attempts
if (this.isConnecting) {
return;
}
this.isConnecting = true;
// Only reset retry counters on fresh connection (not during auto-reconnect)
if (!this.isReconnecting) {
this.currentRetryCount = 0; this.currentRetryCount = 0;
this.currentBackoffDelay = this.initialBackoffDelay; this.currentBackoffDelay = this.initialBackoffDelay;
}
this.isReconnecting = false;
const done = plugins.smartpromise.defer(); const done = plugins.smartpromise.defer();
const smartenvInstance = new plugins.smartenv.Smartenv(); const smartenvInstance = new plugins.smartenv.Smartenv();
const socketIoClient: any = await smartenvInstance.getEnvAwareModule({
nodeModuleName: 'socket.io-client',
webUrlArg: 'https://cdn.jsdelivr.net/npm/socket.io-client@4/dist/socket.io.js',
getFunction: () => {
const socketIoBrowserModule = (globalThis as any).io;
// console.log('loaded socket.io for browser');
return socketIoBrowserModule;
},
});
// console.log(socketIoClient);
logger.log('info', 'trying to connect...'); logger.log('info', 'trying to connect...');
const socketUrl = `${this.serverUrl}:${this.serverPort}`;
// Construct WebSocket URL
const protocol = this.serverUrl.startsWith('https') ? 'wss' : 'ws';
const host = this.serverUrl.replace(/^https?:\/\//, '');
const socketUrl = `${protocol}://${host}:${this.serverPort}`;
// Get WebSocket implementation (native in browser, ws in Node)
let WebSocketClass: typeof WebSocket;
if (typeof WebSocket !== 'undefined') {
// Browser environment
WebSocketClass = WebSocket;
} else {
// Node.js environment
const wsModule = await smartenvInstance.getSafeNodeModule('ws');
WebSocketClass = wsModule.default || wsModule;
}
const socket = new WebSocketClass(socketUrl);
this.currentSocket = socket;
this.socketConnection = new SocketConnection({ this.socketConnection = new SocketConnection({
alias: this.alias, alias: this.alias,
authenticated: false, authenticated: false,
side: 'client', side: 'client',
smartsocketHost: this, smartsocketHost: this,
socket: await socketIoClient socket: socket as any,
.connect(socketUrl, {
multiplex: true,
rememberUpgrade: true,
autoConnect: false,
reconnectionAttempts: 0,
rejectUnauthorized: socketUrl.startsWith('https://localhost') ? false : true,
})
.open(),
}); });
// Increment attempt ID to invalidate any pending timers from previous attempts
this.connectionAttemptId++;
const currentAttemptId = this.connectionAttemptId;
const timer = new plugins.smarttime.Timer(5000); const timer = new plugins.smarttime.Timer(5000);
timer.start(); timer.start();
timer.completed.then(() => { timer.completed.then(() => {
// Only fire timeout if this is still the current connection attempt
if (currentAttemptId === this.connectionAttemptId && this.eventStatus !== 'connected') {
this.updateStatus('timedOut'); this.updateStatus('timedOut');
logger.log('warn', 'connection to server timed out.'); logger.log('warn', 'connection to server timed out.');
this.disconnect(true); this.disconnect(true);
}
}); });
// authentication flow // Handle connection open
this.socketConnection.socket.on('requestAuth', (dataArg: interfaces.IRequestAuthPayload) => { socket.addEventListener('open', () => {
timer.reset(); timer.reset();
logger.log('info', `server ${dataArg.serverAlias} requested authentication`); });
// lets register the authenticated event // Handle messages
this.socketConnection.socket.on('authenticated', async () => { socket.addEventListener('message', async (event: MessageEvent | { data: string }) => {
this.remoteShortId = dataArg.serverAlias; try {
const data = typeof event.data === 'string' ? event.data : event.data.toString();
const message: interfaces.ISocketMessage = JSON.parse(data);
switch (message.type) {
case 'authRequest':
timer.reset();
const authRequestPayload = message.payload as interfaces.IAuthRequestPayload;
logger.log('info', `server ${authRequestPayload.serverAlias} requested authentication`);
this.remoteShortId = authRequestPayload.serverAlias;
// Send authentication data
this.socketConnection.sendMessage({
type: 'auth',
payload: { alias: this.alias },
});
break;
case 'authResponse':
const authResponse = message.payload as interfaces.IAuthResponsePayload;
if (authResponse.success) {
logger.log('info', 'client is authenticated'); logger.log('info', 'client is authenticated');
this.socketConnection.authenticated = true; this.socketConnection.authenticated = true;
await this.socketConnection.listenToFunctionRequests(); } else {
}); logger.log('warn', `authentication failed: ${authResponse.error}`);
await this.disconnect();
}
break;
this.socketConnection.socket.on('serverFullyReactive', async () => { case 'serverReady':
// lets take care of retagging // Set up function request listening
await this.socketConnection.listenToFunctionRequests();
// Handle retagging
const oldTagStore = this.tagStore; const oldTagStore = this.tagStore;
this.tagStoreSubscription?.unsubscribe(); this.tagStoreSubscription?.unsubscribe();
for (const keyArg of Object.keys(this.tagStore)) { for (const keyArg of Object.keys(this.tagStore)) {
@@ -173,39 +220,47 @@ export class SmartsocketClient {
await this.addTag(oldTagStore[tag]); await this.addTag(oldTagStore[tag]);
} }
this.updateStatus('connected'); this.updateStatus('connected');
this.isConnecting = false;
done.resolve(); done.resolve();
break;
default:
// Other messages are handled by SocketConnection
this.socketConnection.handleMessage(message);
break;
}
} catch (err) {
// Not a valid JSON message, ignore
}
}); });
// lets register the forbidden event // Handle disconnection and errors
this.socketConnection.socket.on('forbidden', async () => { const closeHandler = async () => {
logger.log('warn', `disconnecting due to being forbidden to use the ressource`); // Only handle close if this is still the current socket and we're not already disconnecting
await this.disconnect(); if (this.currentSocket === socket && !this.disconnectRunning) {
}); logger.log(
'info',
// lets provide the actual auth data `SocketConnection with >alias ${this.alias} on >side client disconnected`
this.socketConnection.socket.emit('dataAuth', { );
alias: this.alias,
});
});
// handle connection
this.socketConnection.socket.on('connect', async () => {});
// handle disconnection and errors
this.socketConnection.socket.on('disconnect', async () => {
await this.disconnect(true); await this.disconnect(true);
}); }
};
this.socketConnection.socket.on('reconnect_failed', async () => { const errorHandler = async () => {
if (this.currentSocket === socket && !this.disconnectRunning) {
await this.disconnect(true); await this.disconnect(true);
}); }
this.socketConnection.socket.on('connect_error', async () => { };
await this.disconnect(true);
}); socket.addEventListener('close', closeHandler);
socket.addEventListener('error', errorHandler);
return done.promise; return done.promise;
} }
private disconnectRunning = false; private disconnectRunning = false;
private currentSocket: WebSocket | null = null;
private connectionAttemptId = 0; // Increment on each connect attempt to invalidate old timers
/** /**
* disconnect from the server * disconnect from the server
@@ -215,13 +270,19 @@ export class SmartsocketClient {
return; return;
} }
this.disconnectRunning = true; this.disconnectRunning = true;
this.isConnecting = false;
this.updateStatus('disconnecting'); this.updateStatus('disconnecting');
this.tagStoreSubscription?.unsubscribe(); this.tagStoreSubscription?.unsubscribe();
// Store reference to current socket before cleanup
const socketToClose = this.currentSocket;
this.currentSocket = null;
if (this.socketConnection) { if (this.socketConnection) {
await this.socketConnection.disconnect(); await this.socketConnection.disconnect();
this.socketConnection = undefined; this.socketConnection = undefined;
logger.log('ok', 'disconnected socket!'); logger.log('ok', 'disconnected socket!');
} else { } else if (!socketToClose) {
this.disconnectRunning = false; this.disconnectRunning = false;
logger.log('warn', 'tried to disconnect, without a SocketConnection'); logger.log('warn', 'tried to disconnect, without a SocketConnection');
return; return;
@@ -254,6 +315,7 @@ export class SmartsocketClient {
await plugins.smartdelay.delayFor(delay); await plugins.smartdelay.delayFor(delay);
this.disconnectRunning = false; this.disconnectRunning = false;
this.isReconnecting = true;
await this.connect(); await this.connect();
} else { } else {
this.disconnectRunning = false; this.disconnectRunning = false;
@@ -279,7 +341,6 @@ export class SmartsocketClient {
functionNameArg: T['method'], functionNameArg: T['method'],
dataArg: T['request'] dataArg: T['request']
): Promise<T['response']> { ): Promise<T['response']> {
const done = plugins.smartpromise.defer();
const socketRequest = new SocketRequest<T>(this, { const socketRequest = new SocketRequest<T>(this, {
side: 'requesting', side: 'requesting',
originSocketConnection: this.socketConnection, originSocketConnection: this.socketConnection,

View File

@@ -26,7 +26,7 @@ export interface ISocketConnectionConstructorOptions {
authenticated: boolean; authenticated: boolean;
side: TSocketConnectionSide; side: TSocketConnectionSide;
smartsocketHost: Smartsocket | SmartsocketClient; smartsocketHost: Smartsocket | SmartsocketClient;
socket: pluginsTyped.socketIo.Socket | pluginsTyped.socketIoClient.Socket; socket: pluginsTyped.TWebSocket | pluginsTyped.IWebSocketLike;
} }
/** /**
@@ -47,7 +47,7 @@ export class SocketConnection {
public side: TSocketConnectionSide; public side: TSocketConnectionSide;
public authenticated: boolean = false; public authenticated: boolean = false;
public smartsocketRef: Smartsocket | SmartsocketClient; public smartsocketRef: Smartsocket | SmartsocketClient;
public socket: pluginsTyped.socketIo.Socket | pluginsTyped.socketIoClient.Socket; public socket: pluginsTyped.TWebSocket | pluginsTyped.IWebSocketLike;
public eventSubject = new plugins.smartrx.rxjs.Subject<interfaces.TConnectionStatus>(); public eventSubject = new plugins.smartrx.rxjs.Subject<interfaces.TConnectionStatus>();
public eventStatus: interfaces.TConnectionStatus = 'new'; public eventStatus: interfaces.TConnectionStatus = 'new';
@@ -65,20 +65,94 @@ export class SocketConnection {
// standard behaviour that is always true // standard behaviour that is always true
allSocketConnections.add(this); allSocketConnections.add(this);
}
// handle connection /**
this.socket.on('connect', async () => { * Sends a message through the socket
this.updateStatus('connected'); */
public sendMessage(message: interfaces.ISocketMessage): void {
if (this.socket.readyState === 1) { // WebSocket.OPEN
this.socket.send(JSON.stringify(message));
}
}
/**
* Handles incoming messages
*/
public handleMessage(messageData: interfaces.ISocketMessage): void {
switch (messageData.type) {
case 'function':
this.handleFunctionCall(messageData as interfaces.ISocketMessage<interfaces.IFunctionCallPayload>);
break;
case 'functionResponse':
this.handleFunctionResponse(messageData as interfaces.ISocketMessage<interfaces.IFunctionCallPayload>);
break;
case 'tagUpdate':
this.handleTagUpdate(messageData as interfaces.ISocketMessage<interfaces.ITagUpdatePayload>);
break;
default:
// Authentication messages are handled by the server/client classes
break;
}
}
private handleFunctionCall(messageData: interfaces.ISocketMessage<interfaces.IFunctionCallPayload>): void {
const requestData: ISocketRequestDataObject<any> = {
funcCallData: {
funcName: messageData.payload.funcName,
funcDataArg: messageData.payload.funcData,
},
shortId: messageData.id,
};
const referencedFunction: SocketFunction<any> =
this.smartsocketRef.socketFunctions.findSync((socketFunctionArg) => {
return socketFunctionArg.name === requestData.funcCallData.funcName;
}); });
this.socket.on('disconnect', async () => {
logger.log( if (referencedFunction) {
'info', const localSocketRequest = new SocketRequest(this.smartsocketRef, {
`SocketConnection with >alias ${this.alias} on >side ${this.side} disconnected` side: 'responding',
originSocketConnection: this,
shortId: requestData.shortId,
funcCallData: requestData.funcCallData,
});
localSocketRequest.createResponse();
} else {
logger.log('warn', `function ${requestData.funcCallData.funcName} not found or out of scope`);
}
}
private handleFunctionResponse(messageData: interfaces.ISocketMessage<interfaces.IFunctionCallPayload>): void {
const responseData: ISocketRequestDataObject<any> = {
funcCallData: {
funcName: messageData.payload.funcName,
funcDataArg: messageData.payload.funcData,
},
shortId: messageData.id,
};
const targetSocketRequest = SocketRequest.getSocketRequestById(
this.smartsocketRef,
responseData.shortId
); );
await this.disconnect(); if (targetSocketRequest) {
allSocketConnections.remove(this); targetSocketRequest.handleResponse(responseData);
this.eventSubject.next('disconnected'); }
}
private handleTagUpdate(messageData: interfaces.ISocketMessage<interfaces.ITagUpdatePayload>): void {
const tagStoreArg = messageData.payload.tags as interfaces.TTagStore;
if (!plugins.smartjson.deepEqualObjects(this.tagStore, tagStoreArg)) {
this.tagStore = tagStoreArg;
// Echo back to confirm
this.sendMessage({
type: 'tagUpdate',
payload: { tags: this.tagStore },
}); });
this.tagStoreObservable.next(this.tagStore);
}
this.remoteTagStoreObservable.next(tagStoreArg);
} }
/** /**
@@ -99,54 +173,88 @@ export class SocketConnection {
done.resolve(); done.resolve();
} }
}); });
this.socket.emit('updateTagStore', this.tagStore); this.sendMessage({
type: 'tagUpdate',
payload: { tags: this.tagStore },
});
await done.promise; await done.promise;
} }
/** /**
* gets a tag by id * Gets a tag by id
* @param tagIdArg
*/ */
public async getTagById(tagIdArg: interfaces.ITag['id']) { public getTagById(tagIdArg: interfaces.ITag['id']): interfaces.ITag | undefined {
return this.tagStore[tagIdArg]; return this.tagStore[tagIdArg];
} }
/** /**
* removes a tag from a connection * Removes a tag from a connection
*/ */
public async removeTagById(tagIdArg: interfaces.ITag['id']) { public removeTagById(tagIdArg: interfaces.ITag['id']): void {
delete this.tagStore[tagIdArg]; delete this.tagStore[tagIdArg];
this.tagStoreObservable.next(this.tagStore); this.tagStoreObservable.next(this.tagStore);
this.socket.emit('updateTagStore', this.tagStore); this.sendMessage({
type: 'tagUpdate',
payload: { tags: this.tagStore },
});
} }
// authenticating -------------------------- // authenticating --------------------------
/** /**
* authenticate the socket * authenticate the socket (server side)
*/ */
public authenticate() { public authenticate(): Promise<SocketConnection> {
const done = plugins.smartpromise.defer(); const done = plugins.smartpromise.defer<SocketConnection>();
this.socket.on('dataAuth', async (dataArg: ISocketConnectionAuthenticationObject) => {
// Set up message handler for authentication
const messageHandler = (event: pluginsTyped.TMessageEvent) => {
try {
const data = typeof event.data === 'string' ? event.data : event.data.toString();
const message: interfaces.ISocketMessage = JSON.parse(data);
if (message.type === 'auth') {
const authData = message.payload as interfaces.IAuthPayload;
logger.log('info', 'received authentication data...'); logger.log('info', 'received authentication data...');
this.socket.removeAllListeners('dataAuth');
if (dataArg.alias) { if (authData.alias) {
// TODO: authenticate password this.alias = authData.alias;
this.alias = dataArg.alias;
this.authenticated = true; this.authenticated = true;
this.socket.emit('authenticated');
// Send authentication response
this.sendMessage({
type: 'authResponse',
payload: { success: true },
});
logger.log('ok', `socket with >>alias ${this.alias} is authenticated!`); logger.log('ok', `socket with >>alias ${this.alias} is authenticated!`);
done.resolve(this); done.resolve(this);
} else { } else {
this.authenticated = false; this.authenticated = false;
await this.disconnect(); this.sendMessage({
done.reject('a socket tried to connect, but could not authenticated.'); type: 'authResponse',
} payload: { success: false, error: 'No alias provided' },
}); });
const requestAuthPayload: interfaces.IRequestAuthPayload = { this.disconnect();
serverAlias: this.smartsocketRef.alias, done.reject('a socket tried to connect, but could not authenticate.');
}
}
} catch (err) {
logger.log('warn', `Failed to parse auth message: ${err instanceof Error ? err.message : String(err)}`);
}
}; };
this.socket.emit('requestAuth', requestAuthPayload);
(this.socket as pluginsTyped.IWebSocketLike).addEventListener('message', messageHandler);
// Request authentication
const requestAuthPayload: interfaces.TAuthRequestMessage = {
type: 'authRequest',
payload: {
serverAlias: (this.smartsocketRef as Smartsocket).alias,
},
};
this.sendMessage(requestAuthPayload);
return done.promise; return done.promise;
} }
@@ -158,43 +266,18 @@ export class SocketConnection {
public listenToFunctionRequests() { public listenToFunctionRequests() {
const done = plugins.smartpromise.defer(); const done = plugins.smartpromise.defer();
if (this.authenticated) { if (this.authenticated) {
this.socket.on('function', (dataArg: ISocketRequestDataObject<any>) => { // Set up message handler for all messages
// check if requested function is available to the socket's scope const messageHandler = (event: pluginsTyped.TMessageEvent) => {
// logger.log('info', 'function request received'); try {
const referencedFunction: SocketFunction<any> = const data = typeof event.data === 'string' ? event.data : event.data.toString();
this.smartsocketRef.socketFunctions.findSync((socketFunctionArg) => { const message: interfaces.ISocketMessage = JSON.parse(data);
return socketFunctionArg.name === dataArg.funcCallData.funcName; this.handleMessage(message);
}); } catch (err) {
if (referencedFunction) { logger.log('warn', `Failed to parse socket message: ${err instanceof Error ? err.message : String(err)}`);
// logger.log('ok', 'function in access scope');
const localSocketRequest = new SocketRequest(this.smartsocketRef, {
side: 'responding',
originSocketConnection: this,
shortId: dataArg.shortId,
funcCallData: dataArg.funcCallData,
});
localSocketRequest.createResponse(); // takes care of creating response and sending it back
} else {
logger.log('warn', 'function not existent or out of access scope');
} }
}); };
this.socket.on('functionResponse', (dataArg: ISocketRequestDataObject<any>) => {
// logger.log('info', `received response for request with id ${dataArg.shortId}`);
const targetSocketRequest = SocketRequest.getSocketRequestById(
this.smartsocketRef,
dataArg.shortId
);
targetSocketRequest.handleResponse(dataArg);
});
this.socket.on('updateTagStore', async (tagStoreArg: interfaces.TTagStore) => { (this.socket as pluginsTyped.IWebSocketLike).addEventListener('message', messageHandler);
if (!plugins.smartjson.deepEqualObjects(this.tagStore, tagStoreArg)) {
this.tagStore = tagStoreArg;
this.socket.emit('updateTagStore', this.tagStore);
this.tagStoreObservable.next(this.tagStore);
}
this.remoteTagStoreObservable.next(tagStoreArg);
});
logger.log( logger.log(
'info', 'info',
@@ -211,7 +294,10 @@ export class SocketConnection {
// disconnecting ---------------------- // disconnecting ----------------------
public async disconnect() { public async disconnect() {
this.socket.disconnect(true); if (this.socket.readyState === 1 || this.socket.readyState === 0) {
this.socket.close();
}
allSocketConnections.remove(this);
this.updateStatus('disconnected'); this.updateStatus('disconnected');
} }

View File

@@ -1,4 +1,5 @@
import * as plugins from './smartsocket.plugins.js'; import * as plugins from './smartsocket.plugins.js';
import * as interfaces from './interfaces/index.js';
// import interfaces // import interfaces
import { import {
@@ -78,11 +79,15 @@ export class SocketRequest<T extends plugins.typedrequestInterfaces.ITypedReques
* dispatches a socketrequest from the requesting to the receiving side * dispatches a socketrequest from the requesting to the receiving side
*/ */
public dispatch(): Promise<ISocketFunctionCallDataResponse<T>> { public dispatch(): Promise<ISocketFunctionCallDataResponse<T>> {
const requestData: ISocketRequestDataObject<T> = { const message: interfaces.ISocketMessage<interfaces.IFunctionCallPayload> = {
funcCallData: this.funcCallData, type: 'function',
shortId: this.shortid, id: this.shortid,
payload: {
funcName: this.funcCallData.funcName,
funcData: this.funcCallData.funcDataArg,
},
}; };
this.originSocketConnection.socket.emit('function', requestData); this.originSocketConnection.sendMessage(message);
return this.done.promise; return this.done.promise;
} }
@@ -90,7 +95,6 @@ export class SocketRequest<T extends plugins.typedrequestInterfaces.ITypedReques
* handles the response that is received by the requesting side * handles the response that is received by the requesting side
*/ */
public async handleResponse(responseDataArg: ISocketRequestDataObject<T>) { public async handleResponse(responseDataArg: ISocketRequestDataObject<T>) {
// logger.log('info', 'handling response!');
this.done.resolve(responseDataArg.funcCallData); this.done.resolve(responseDataArg.funcCallData);
this.smartsocketRef.socketRequests.remove(this); this.smartsocketRef.socketRequests.remove(this);
} }
@@ -110,16 +114,23 @@ export class SocketRequest<T extends plugins.typedrequestInterfaces.ITypedReques
logger.log('error', `There is no SocketFunction defined for ${this.funcCallData.funcName}`); logger.log('error', `There is no SocketFunction defined for ${this.funcCallData.funcName}`);
return; return;
} }
// logger.log('info', `invoking ${targetSocketFunction.name}`);
targetSocketFunction targetSocketFunction
.invoke(this.funcCallData, this.originSocketConnection) .invoke(this.funcCallData, this.originSocketConnection)
.then((resultData) => { .then((resultData) => {
// logger.log('info', 'got resultData. Sending it to requesting party.'); const message: interfaces.ISocketMessage<interfaces.IFunctionCallPayload> = {
const responseData: ISocketRequestDataObject<T> = { type: 'functionResponse',
funcCallData: resultData, id: this.shortid,
shortId: this.shortid, payload: {
funcName: resultData.funcName,
funcData: resultData.funcDataArg,
},
}; };
this.originSocketConnection.socket.emit('functionResponse', responseData); this.originSocketConnection.sendMessage(message);
this.smartsocketRef.socketRequests.remove(this);
})
.catch((error) => {
logger.log('error', `Function invocation failed for ${this.funcCallData.funcName}: ${error instanceof Error ? error.message : String(error)}`);
this.smartsocketRef.socketRequests.remove(this); this.smartsocketRef.socketRequests.remove(this);
}); });
} }

View File

@@ -6,16 +6,16 @@ import { Smartsocket } from './smartsocket.classes.smartsocket.js';
import { logger } from './smartsocket.logging.js'; import { logger } from './smartsocket.logging.js';
/** /**
* class socketServer * class SocketServer
* handles the attachment of socketIo to whatever server is in play * handles the WebSocket server in standalone mode, or provides hooks for smartserve integration
*/ */
export class SocketServer { export class SocketServer {
private smartsocket: Smartsocket; private smartsocket: Smartsocket;
private httpServerDeferred: plugins.smartpromise.Deferred<any>;
private httpServer: pluginsTyped.http.Server | pluginsTyped.https.Server; private httpServer: pluginsTyped.http.Server | pluginsTyped.https.Server;
private wsServer: pluginsTyped.ws.WebSocketServer;
/** /**
* wether httpServer is standalone * whether httpServer is standalone (created by us)
*/ */
private standaloneServer = false; private standaloneServer = false;
@@ -24,71 +24,180 @@ export class SocketServer {
} }
/** /**
* starts the server with another server * Starts listening to incoming websocket connections (standalone mode).
* also works with an express style server * If no port is specified, this is a no-op (hooks mode via smartserve).
*/
public async setExternalServer(
serverType: 'smartexpress',
serverArg: pluginsTyped.typedserver.servertools.Server
) {
this.httpServerDeferred = plugins.smartpromise.defer();
await serverArg.startedPromise;
this.httpServer = serverArg.httpServer;
this.httpServerDeferred.resolve();
}
/**
* gets the server for socket.io
*/
public async getServerForSocketIo() {
if (this.httpServerDeferred) {
await this.httpServerDeferred.promise;
}
if (this.httpServer) {
return this.httpServer;
} else {
const httpModule = await this.smartsocket.smartenv.getSafeNodeModule('http');
this.httpServer = new httpModule.Server();
this.standaloneServer = true;
return this.httpServer;
}
}
/**
* starts listening to incoming sockets:
*/ */
public async start() { public async start() {
const done = plugins.smartpromise.defer(); // If no port specified, we're in hooks mode - nothing to start
// handle http servers
// in case an external server has been set "this.standaloneServer" should be false
if (this.httpServer && this.standaloneServer) {
if (!this.smartsocket.options.port) { if (!this.smartsocket.options.port) {
logger.log('error', 'there should be a port specifed for smartsocket!'); return;
throw new Error('there should be a port specified for smartsocket');
} }
// Standalone mode - create our own HTTP server and WebSocket server
const done = plugins.smartpromise.defer();
const httpModule = await this.smartsocket.smartenv.getSafeNodeModule('http');
const wsModule = await this.smartsocket.smartenv.getSafeNodeModule('ws');
this.httpServer = httpModule.createServer();
this.standaloneServer = true;
// Create WebSocket server attached to HTTP server
this.wsServer = new wsModule.WebSocketServer({ server: this.httpServer });
this.wsServer.on('connection', (ws: pluginsTyped.ws.WebSocket) => {
this.smartsocket.handleNewConnection(ws);
});
this.httpServer.listen(this.smartsocket.options.port, () => { this.httpServer.listen(this.smartsocket.options.port, () => {
logger.log( logger.log(
'success', 'success',
`Server started in standalone mode on ${this.smartsocket.options.port}` `Server started in standalone mode on port ${this.smartsocket.options.port}`
); );
done.resolve(); done.resolve();
}); });
} else {
done.resolve();
}
// nothing else to do if express server is set
await done.promise; await done.promise;
return;
} }
/** /**
* closes the server * closes the server
*/ */
public async stop() { public async stop() {
if (this.httpServer) { const done = plugins.smartpromise.defer<void>();
this.httpServer.close(); let resolved = false;
if (this.wsServer) {
// Close all WebSocket connections
this.wsServer.clients.forEach((client) => {
client.terminate();
});
this.wsServer.close();
this.wsServer = null;
} }
if (this.httpServer && this.standaloneServer) {
const resolveOnce = () => {
if (!resolved) {
resolved = true;
this.httpServer = null;
this.standaloneServer = false;
done.resolve();
}
};
this.httpServer.close(() => {
resolveOnce();
});
// Add a timeout in case close callback doesn't fire
const timeoutId = setTimeout(() => {
resolveOnce();
}, 2000);
// Ensure timeout doesn't keep process alive
if (timeoutId.unref) {
timeoutId.unref();
}
} else {
done.resolve();
}
await done.promise;
}
/**
* Returns WebSocket hooks for integration with smartserve.
* Pass these hooks to SmartServe's websocket config.
*/
public getSmartserveWebSocketHooks(): pluginsTyped.ISmartserveWebSocketHooks {
return {
onOpen: async (peer: pluginsTyped.ISmartserveWebSocketPeer) => {
// Create a wrapper that adapts ISmartserveWebSocketPeer to WebSocket-like interface
const wsLikeSocket = this.createWsLikeFromPeer(peer);
await this.smartsocket.handleNewConnection(wsLikeSocket);
},
onMessage: async (peer: pluginsTyped.ISmartserveWebSocketPeer, message: pluginsTyped.ISmartserveWebSocketMessage) => {
// Dispatch message to the SocketConnection via the adapter
const adapter = peer.data.get('smartsocket_adapter') as any;
if (adapter) {
let textData: string | undefined;
if (message.type === 'text' && message.text) {
textData = message.text;
} else if (message.type === 'binary' && message.data) {
// Convert binary to text (Buffer/Uint8Array to string)
textData = new TextDecoder().decode(message.data);
}
if (textData) {
adapter.dispatchMessage(textData);
}
}
},
onClose: async (peer: pluginsTyped.ISmartserveWebSocketPeer, code: number, reason: string) => {
// Dispatch close to the SocketConnection via the adapter
const adapter = peer.data.get('smartsocket_adapter') as any;
if (adapter) {
adapter.dispatchClose();
}
},
onError: async (peer: pluginsTyped.ISmartserveWebSocketPeer, error: Error) => {
// Dispatch error to the SocketConnection via the adapter
const adapter = peer.data.get('smartsocket_adapter') as any;
if (adapter) {
adapter.dispatchError();
}
},
};
}
/**
* Creates a WebSocket-like object from a smartserve peer
* This allows our SocketConnection to work with both native WebSocket and smartserve peers
*/
private createWsLikeFromPeer(peer: pluginsTyped.ISmartserveWebSocketPeer): pluginsTyped.IWebSocketLike {
const messageListeners: Array<(event: pluginsTyped.TMessageEvent) => void> = [];
const closeListeners: Array<() => void> = [];
const errorListeners: Array<() => void> = [];
// Store the adapter on the peer for message routing
peer.data.set('smartsocket_adapter', {
dispatchMessage: (data: string) => {
messageListeners.forEach((listener) => {
listener({ data });
});
},
dispatchClose: () => {
closeListeners.forEach((listener) => listener());
},
dispatchError: () => {
errorListeners.forEach((listener) => listener());
},
});
return {
get readyState() { return peer.readyState; },
send: (data: string) => peer.send(data),
close: (code?: number, reason?: string) => peer.close(code, reason),
addEventListener: (event: string, listener: any) => {
if (event === 'message') {
messageListeners.push(listener);
} else if (event === 'close') {
closeListeners.push(listener);
} else if (event === 'error') {
errorListeners.push(listener);
}
},
removeEventListener: (event: string, listener: any) => {
if (event === 'message') {
const idx = messageListeners.indexOf(listener);
if (idx >= 0) messageListeners.splice(idx, 1);
} else if (event === 'close') {
const idx = closeListeners.indexOf(listener);
if (idx >= 0) closeListeners.splice(idx, 1);
} else if (event === 'error') {
const idx = errorListeners.indexOf(listener);
if (idx >= 0) errorListeners.splice(idx, 1);
}
},
};
} }
} }

View File

@@ -4,20 +4,66 @@ import type * as https from 'https';
export type { http, https }; export type { http, https };
// pushrocks scope // third party scope - ws types
import type * as typedserver from '@api.global/typedserver'; import type * as wsTypes from 'ws';
export type { typedserver }; export namespace ws {
export type WebSocket = wsTypes.WebSocket;
// third party scope export type WebSocketServer = wsTypes.WebSocketServer;
import type { Socket as ServerSocket, Server as ServerServer } from 'socket.io'; export type RawData = wsTypes.RawData;
import type { Socket as ClientSocket, connect as ClientIo } from 'socket.io-client';
export namespace socketIo {
export type Socket = ServerSocket;
export type Server = ServerServer;
} }
export namespace socketIoClient {
export type Socket = ClientSocket; /**
export type connect = typeof ClientIo; * Unified WebSocket type supporting both browser and Node.js environments
*/
export type TWebSocket = WebSocket | ws.WebSocket;
/**
* Message event type for WebSocket messages (browser and Node.js compatible)
*/
export type TMessageEvent = MessageEvent | { data: string };
/**
* WebSocket-like interface for adapters (e.g., smartserve peer adapter)
*/
export interface IWebSocketLike {
readyState: number;
send(data: string): void;
close(code?: number, reason?: string): void;
addEventListener(event: 'message', listener: (event: TMessageEvent) => void): void;
addEventListener(event: 'close', listener: () => void): void;
addEventListener(event: 'error', listener: () => void): void;
removeEventListener?(event: string, listener: (...args: any[]) => void): void;
}
// smartserve compatibility interface (for setExternalServer)
// This mirrors the IWebSocketPeer interface from smartserve
export interface ISmartserveWebSocketPeer {
id: string;
url: string;
readyState: 0 | 1 | 2 | 3;
protocol: string;
extensions: string;
send(data: string): void;
sendBinary(data: Uint8Array | ArrayBuffer): void;
close(code?: number, reason?: string): void;
ping(data?: Uint8Array): void;
terminate(): void;
context: any;
data: Map<string, unknown>;
tags: Set<string>;
}
export interface ISmartserveWebSocketMessage {
type: 'text' | 'binary';
text?: string;
data?: Uint8Array;
size: number;
}
export interface ISmartserveWebSocketHooks {
onOpen?: (peer: ISmartserveWebSocketPeer) => void | Promise<void>;
onMessage?: (peer: ISmartserveWebSocketPeer, message: ISmartserveWebSocketMessage) => void | Promise<void>;
onClose?: (peer: ISmartserveWebSocketPeer, code: number, reason: string) => void | Promise<void>;
onError?: (peer: ISmartserveWebSocketPeer, error: Error) => void | Promise<void>;
} }