Compare commits
21 Commits
Author | SHA1 | Date | |
---|---|---|---|
ee59471e14 | |||
da10b25214 | |||
933f09d632 | |||
eb330eaf7a | |||
c2e856821d | |||
653af3a3e7 | |||
4552a0527d | |||
e39141e86b | |||
bf6bda88e5 | |||
fb555b33be | |||
2e2826c52d | |||
bca3bd92a5 | |||
adc3f0935f | |||
72430fdb0d | |||
ee827dd5b3 | |||
2aefae00de | |||
6753a4fefc | |||
8c5428baf8 | |||
69c1ad04dc | |||
61d5301de8 | |||
72fa7f790c |
@ -119,6 +119,6 @@ jobs:
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
pnpm install -g @gitzone/tsdoc
|
||||
pnpm install -g @git.zone/tsdoc
|
||||
npmci command tsdoc
|
||||
continue-on-error: true
|
||||
|
103
changelog.md
Normal file
103
changelog.md
Normal file
@ -0,0 +1,103 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-03-10 - 2.1.0 - feat(SmartsocketClient)
|
||||
Improve client reconnection logic with exponential backoff and jitter; update socket.io and @types/node dependencies
|
||||
|
||||
- Bump engine.io from 6.5.4 to 6.6.4, socket.io and socket.io-client from 4.7.5 to 4.8.1
|
||||
- Bump @types/node from ^20.12.7 to ^22.13.10
|
||||
- Add new optional reconnection parameters (maxRetries, initialBackoffDelay, maxBackoffDelay) to SmartsocketClient options
|
||||
- Implement exponential backoff with jitter for auto-reconnect and reset reconnection state on successful connection
|
||||
|
||||
## 2024-05-29 - 2.0.27 - docs
|
||||
update description
|
||||
|
||||
## 2024-04-26 to 2024-03-30 - 2.0.26 … 2.0.24 - core & configuration
|
||||
A series of internal fixes and configuration tweaks.
|
||||
- fix(core): update
|
||||
- update tsconfig
|
||||
- update npmextra.json: githost
|
||||
|
||||
## 2023-09-10 to 2023-07-21 - 2.0.23 … 2.0.20 - core
|
||||
Multiple minor core fixes were applied in rapid succession.
|
||||
- fix(core): update
|
||||
|
||||
## 2023-07-21 to 2023-03-20 - 2.0.19 … 2.0.15 - core
|
||||
Routine internal updates addressing core functionality.
|
||||
- fix(core): update
|
||||
|
||||
## 2023-02-07 to 2022-03-24 - 2.0.14 … 2.0.0 - core
|
||||
Further minor core updates were rolled out over several versions.
|
||||
- fix(core): update
|
||||
|
||||
## 2022-03-14 - 1.2.22 - esm
|
||||
A breaking change was introduced to switch the module system.
|
||||
- BREAKING CHANGE(switch to esm): update
|
||||
|
||||
## 2022-01-20 to 2021-01-23 - 1.2.21 … 1.2.0 - core
|
||||
A range of minor core fixes.
|
||||
- fix(core): update
|
||||
|
||||
## 2020-12-26 - 1.1.71 - SmartsocketClient
|
||||
New functionality in the socket client was added.
|
||||
- feat(SmartsocketClient): socket client can now be stopped with .stop() in addition to .reconnect()
|
||||
|
||||
## 2020-12-26 to 2020-09-24 - 1.1.70 … 1.1.58 - core & test
|
||||
A group of updates addressing both core mechanics and tests.
|
||||
- fix(core): update
|
||||
- fix(test): use @pushrocks/isohash instead of @pushrocks/smarthash
|
||||
|
||||
## 2019-11-08 to 2019-04-23 - 1.1.57 … 1.1.27 - core
|
||||
Numerous versions in this period included only internal core fixes.
|
||||
- fix(core): update
|
||||
|
||||
## 2019-01-31 to 2019-01-30 - 1.1.26 … 1.1.19 - build, docs & configuration
|
||||
Updates went beyond the core, affecting build tooling and package metadata.
|
||||
- fix(build): now building with tsbuild
|
||||
- fix(readme): update
|
||||
- fix(npmextra): adjust access level
|
||||
- fix(scope): switch to @pushrocks
|
||||
- fix(package.json): private setting
|
||||
- fix(snyk): add .snyk file
|
||||
- fix(structure): update to latest standards
|
||||
|
||||
## 2018-03-19 to 2018-03-15 - 1.1.18 … 1.1.12 - core & docs
|
||||
Several improvements touching both functionality and documentation.
|
||||
- now working as expected
|
||||
- start transitioning to better SocketFunction handling
|
||||
- add @types/node
|
||||
- format and update README
|
||||
- update to latest standards
|
||||
|
||||
## 2017-10-09 to 2017-07-07 - 1.1.11 … 1.1.07 - core & docs
|
||||
Updates in this range improved both the internal mechanics and the developer‐facing materials.
|
||||
- allow setting of specific server
|
||||
- fix not ending error correctly
|
||||
- update to newest version
|
||||
- update docs and tests
|
||||
- remove taskbuffer
|
||||
- update to latest standards
|
||||
|
||||
## 2016-09-25 to 2016-09-03 - 1.1.6 … 1.1.3 - docs & core
|
||||
Minor improvements in documentation and code quality.
|
||||
- improve README
|
||||
- added docs
|
||||
- fix scoping of socket roles and perform small syntax fixes
|
||||
|
||||
## 2016-09-02 to 2016-08-16 - 1.1.2 … 1.1.1 - dependencies & security
|
||||
Several housekeeping tasks to update dependencies and improve security.
|
||||
- updated dependencies and exported socketConnection
|
||||
- now authenticating sockets by checking the password hash
|
||||
|
||||
## 2016-08-15 - 1.1.0 - docs
|
||||
A documentation update was published.
|
||||
- update README
|
||||
|
||||
## 2016-08-15 - 1.0.7 - networking
|
||||
A key update made the socket client work bi-directionally, enabling mesh setups.
|
||||
- now working in both directions so mesh setups work
|
||||
|
||||
## 2016-08-14 to 2016-08-07 - 1.0.6 … 1.0.0 - internal changes
|
||||
From the initial release onward, several internal improvements were introduced:
|
||||
- updated tests and structure
|
||||
- reworked reconnection logic and added a request/response abstraction for transparent function calls
|
||||
- initial release features with updated documentation and structure
|
@ -2,17 +2,32 @@
|
||||
"gitzone": {
|
||||
"projectType": "npm",
|
||||
"module": {
|
||||
"githost": "gitlab.com",
|
||||
"githost": "code.foss.global",
|
||||
"gitscope": "push.rocks",
|
||||
"gitrepo": "smartsocket",
|
||||
"description": "easy and secure websocket communication",
|
||||
"description": "Provides easy and secure websocket communication mechanisms, including server and client implementation, function call routing, connection management, and tagging.",
|
||||
"npmPackagename": "@push.rocks/smartsocket",
|
||||
"license": "MIT",
|
||||
"projectDomain": "push.rocks"
|
||||
"projectDomain": "push.rocks",
|
||||
"keywords": [
|
||||
"websocket",
|
||||
"communication",
|
||||
"server",
|
||||
"client",
|
||||
"socket.io",
|
||||
"authentication",
|
||||
"reconnection",
|
||||
"tagging",
|
||||
"function routing",
|
||||
"secure"
|
||||
]
|
||||
}
|
||||
},
|
||||
"npmci": {
|
||||
"npmGlobalTools": [],
|
||||
"npmAccessLevel": "public"
|
||||
},
|
||||
"tsdoc": {
|
||||
"legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
|
||||
}
|
||||
}
|
52
package.json
52
package.json
@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@push.rocks/smartsocket",
|
||||
"version": "2.0.20",
|
||||
"description": "easy and secure websocket communication",
|
||||
"version": "2.1.0",
|
||||
"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",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"type": "module",
|
||||
@ -12,38 +12,38 @@
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+ssh://git@gitlab.com/pushrocks/smartsocket.git"
|
||||
"url": "https://code.foss.global/push.rocks/smartsocket.git"
|
||||
},
|
||||
"author": "Lossless GmbH",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://gitlab.com/pushrocks/smartsocket/issues"
|
||||
},
|
||||
"homepage": "https://gitlab.com/pushrocks/smartsocket#README",
|
||||
"homepage": "https://code.foss.global/push.rocks/smartsocket",
|
||||
"dependencies": {
|
||||
"@apiglobal/typedrequest-interfaces": "^2.0.1",
|
||||
"@apiglobal/typedserver": "^2.0.65",
|
||||
"@api.global/typedrequest-interfaces": "^3.0.18",
|
||||
"@api.global/typedserver": "^3.0.27",
|
||||
"@push.rocks/isohash": "^2.0.0",
|
||||
"@push.rocks/isounique": "^1.0.5",
|
||||
"@push.rocks/lik": "^6.0.3",
|
||||
"@push.rocks/lik": "^6.0.14",
|
||||
"@push.rocks/smartdelay": "^3.0.5",
|
||||
"@push.rocks/smartenv": "^5.0.5",
|
||||
"@push.rocks/smartjson": "^5.0.1",
|
||||
"@push.rocks/smartenv": "^5.0.12",
|
||||
"@push.rocks/smartjson": "^5.0.19",
|
||||
"@push.rocks/smartlog": "^3.0.3",
|
||||
"@push.rocks/smartpromise": "^4.0.3",
|
||||
"@push.rocks/smartrx": "^3.0.3",
|
||||
"@push.rocks/smarttime": "^4.0.1",
|
||||
"engine.io": "6.3.1",
|
||||
"socket.io": "4.5.4",
|
||||
"socket.io-client": "4.5.4"
|
||||
"@push.rocks/smartrx": "^3.0.7",
|
||||
"@push.rocks/smarttime": "^4.0.6",
|
||||
"engine.io": "6.6.4",
|
||||
"socket.io": "4.8.1",
|
||||
"socket.io-client": "4.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@gitzone/tsbuild": "^2.1.66",
|
||||
"@gitzone/tsbundle": "^2.0.8",
|
||||
"@gitzone/tsrun": "^1.2.44",
|
||||
"@gitzone/tstest": "^1.0.77",
|
||||
"@push.rocks/tapbundle": "^5.0.12",
|
||||
"@types/node": "^20.4.2"
|
||||
"@git.zone/tsbuild": "^2.1.66",
|
||||
"@git.zone/tsbundle": "^2.0.8",
|
||||
"@git.zone/tsrun": "^1.2.44",
|
||||
"@git.zone/tstest": "^1.0.77",
|
||||
"@push.rocks/tapbundle": "^5.0.23",
|
||||
"@types/node": "^22.13.10"
|
||||
},
|
||||
"private": false,
|
||||
"files": [
|
||||
@ -60,5 +60,17 @@
|
||||
],
|
||||
"browserslist": [
|
||||
"last 1 chrome versions"
|
||||
],
|
||||
"keywords": [
|
||||
"websocket",
|
||||
"communication",
|
||||
"server",
|
||||
"client",
|
||||
"socket.io",
|
||||
"authentication",
|
||||
"reconnection",
|
||||
"tagging",
|
||||
"function routing",
|
||||
"secure"
|
||||
]
|
||||
}
|
||||
|
11748
pnpm-lock.yaml
generated
11748
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
1
readme.hints.md
Normal file
1
readme.hints.md
Normal file
@ -0,0 +1 @@
|
||||
|
225
readme.md
225
readme.md
@ -1,120 +1,149 @@
|
||||
# @push.rocks/smartsocket
|
||||
easy and secure websocket communication
|
||||
|
||||
## Availabililty and Links
|
||||
* [npmjs.org (npm package)](https://www.npmjs.com/package/@push.rocks/smartsocket)
|
||||
* [gitlab.com (source)](https://gitlab.com/push.rocks/smartsocket)
|
||||
* [github.com (source mirror)](https://github.com/push.rocks/smartsocket)
|
||||
* [docs (typedoc)](https://push.rocks.gitlab.io/smartsocket/)
|
||||
## Install
|
||||
|
||||
## Status for master
|
||||
To install @push.rocks/smartsocket, you can use npm or yarn as follows:
|
||||
|
||||
Status Category | Status Badge
|
||||
-- | --
|
||||
GitLab Pipelines | [](https://lossless.cloud)
|
||||
GitLab Pipline Test Coverage | [](https://lossless.cloud)
|
||||
npm | [](https://lossless.cloud)
|
||||
Snyk | [](https://lossless.cloud)
|
||||
TypeScript Support | [](https://lossless.cloud)
|
||||
node Support | [](https://nodejs.org/dist/latest-v10.x/docs/api/)
|
||||
Code Style | [](https://lossless.cloud)
|
||||
PackagePhobia (total standalone install weight) | [](https://lossless.cloud)
|
||||
PackagePhobia (package size on registry) | [](https://lossless.cloud)
|
||||
BundlePhobia (total size when bundled) | [](https://lossless.cloud)
|
||||
```shell
|
||||
npm install @push.rocks/smartsocket --save
|
||||
```
|
||||
or
|
||||
```shell
|
||||
yarn add @push.rocks/smartsocket
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Use TypeScript for best in class instellisense.
|
||||
@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.
|
||||
|
||||
Under the hood we use socket.io and shortid for managed data exchange.
|
||||
### Getting Started
|
||||
|
||||
### Serverside
|
||||
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
|
||||
import * as smartsocket from 'smartsocket';
|
||||
import * as q from q; // q is a promise library
|
||||
import { Smartsocket } from '@push.rocks/smartsocket';
|
||||
|
||||
// The "Smartsocket" listens on a port and can receive new "SocketConnection" requests.
|
||||
let mySmartsocket = new smartsocket.Smartsocket({
|
||||
port: 3000, // the port smartsocket will listen on
|
||||
// Create a new instance of Smartsocket for the server.
|
||||
const server = new Smartsocket({ alias: 'myServer' });
|
||||
|
||||
// Define a SocketFunction that clients can call
|
||||
server.addSocketFunction({
|
||||
funcName: 'greet',
|
||||
funcDef: async (data) => {
|
||||
console.log(`Server received: ${data.message}`);
|
||||
return { reply: `Hello, ${data.name}!` };
|
||||
}
|
||||
});
|
||||
|
||||
// optional:
|
||||
// run this with anothoer existing server like express
|
||||
declare var someExpressServer; // read the express docs about how express actually works
|
||||
mySmartsocket.setServer(someExpressServer);
|
||||
|
||||
// A "SocketRole" can be referenced by "SocketFunction"s.
|
||||
// All "SocketRequest"s carry authentication data for a specific "SocketRole".
|
||||
// "SocketFunction"s know which "SocketRole"s are allowed to execute them
|
||||
let mySocketRole = new smartsocket.SocketRole({
|
||||
name: 'someRoleName',
|
||||
passwordHash: 'someHashedString',
|
||||
});
|
||||
|
||||
// A "SocketFunction" executes a referenced function and passes in any data of the corresponding "SocketRequest".
|
||||
// The referenced function must return a promise and resolve with data of type any.
|
||||
// Any "SocketRequest" carries a unique identifier. If the referenced function's promise resolved any passed on argument will be returned to the requesting party
|
||||
let testSocketFunction1 = new smartsocket.SocketFunction({
|
||||
funcName: 'testSocketFunction1',
|
||||
funcDef: (data) => {
|
||||
console.log('testSocketFunction1 executed successfully!');
|
||||
},
|
||||
allowedRoles: [mySocketRole], // all roles that have access to a specific function
|
||||
});
|
||||
|
||||
// A "Smartsocket" exposes a .clientCall() that gets
|
||||
// 1. the name of the "SocketFunction" on the client side
|
||||
// 2. the data to pass in
|
||||
// 3. And a target "SocketConnection" (there can be multiple connections at once)
|
||||
// any unique id association is done internally
|
||||
mySmartsocket.clientCall('restart', data, someTargetConnection).then((responseData) => {});
|
||||
```
|
||||
|
||||
#### Client side
|
||||
|
||||
```typescript
|
||||
import * as smartsocket from 'smartsocket';
|
||||
|
||||
// A "SmartsocketClient" is different from a "Smartsocket" in that it doesn't expose any public address.
|
||||
// Thus any new "SocketConnection"s must be innitiated from a "SmartsocketClient".
|
||||
let testSmartsocketClient = new smartsocket.SmartsocketClient({
|
||||
port: testConfig.port,
|
||||
url: 'http://localhost',
|
||||
password: 'testPassword',
|
||||
alias: 'testClient1',
|
||||
role: 'testRole1',
|
||||
});
|
||||
|
||||
// You can .connect() and .disconnect() from a "Smartsocket"
|
||||
testSmartsocketClient.connect().then(() => {
|
||||
done();
|
||||
});
|
||||
|
||||
// The client can also specify "SocketFunction"s. It can also specify "SocketRole"s in case a client connects to multiple servers at once
|
||||
let testSocketFunction2 = new smartsocket.SocketFunction({
|
||||
funcName: 'testSocketFunction2',
|
||||
funcDef: (data) => {}, // the function to execute, has to return promise
|
||||
allowedRoles: [],
|
||||
});
|
||||
|
||||
// A "SmartsocketClient" can call functions on the serverside using .serverCall() analog to the "Smartsocket"'s .clientCall method.
|
||||
mySmartsocketClient.serverCall('function', functionCallData).then((functionResponseData) => {
|
||||
// the functionResponseData comes from the server... awesome, right?
|
||||
// Start the Smartsocket server
|
||||
server.start().then(() => {
|
||||
console.log('WebSocket server is running...');
|
||||
});
|
||||
```
|
||||
|
||||
> **NOTE:**
|
||||
> you can easily chain dependent requests on either the server or client side with promises.
|
||||
> `data` is always a js object that you can design for your specific needs.
|
||||
> It supports buffers for large binary data network exchange.
|
||||
### Creating a WebSocket Client
|
||||
|
||||
## Contribution
|
||||
Create a client that connects to the WebSocket server and interacts with it:
|
||||
|
||||
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
|
||||
```typescript
|
||||
import { SmartsocketClient } from '@push.rocks/smartsocket';
|
||||
|
||||
For further information read the linked docs at the top of this readme.
|
||||
// Create a SmartsocketClient instance and connect to the server
|
||||
const client = new SmartsocketClient({
|
||||
url: 'ws://localhost',
|
||||
port: 3000,
|
||||
alias: 'myClient'
|
||||
});
|
||||
|
||||
## Legal
|
||||
> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
|
||||
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
|
||||
client.connect().then(() => {
|
||||
console.log('Connected to WebSocket server');
|
||||
});
|
||||
|
||||
// Define a function to call the server's 'greet' function
|
||||
async function greetServer(name) {
|
||||
const response = await client.serverCall('greet', { name: name, message: 'Hello!' });
|
||||
console.log(`Server replied: ${response.reply}`);
|
||||
}
|
||||
|
||||
// Use the function
|
||||
greetServer('Alice');
|
||||
```
|
||||
|
||||
### Handling Disconnections and Reconnections
|
||||
|
||||
@push.rocks/smartsocket provides mechanisms to handle client disconnections and attempt reconnections:
|
||||
|
||||
```typescript
|
||||
client.on('disconnect', () => {
|
||||
console.log('Disconnected from server. Attempting to reconnect...');
|
||||
client.connect();
|
||||
});
|
||||
```
|
||||
|
||||
### Sending Binary Data
|
||||
|
||||
The library supports the transmission of binary data efficiently:
|
||||
|
||||
```typescript
|
||||
import fs from 'fs';
|
||||
|
||||
// Function to send a binary file to the server
|
||||
async function sendBinaryData(filePath) {
|
||||
const fileBuffer = fs.readFileSync(filePath);
|
||||
await client.serverCall('sendFile', { file: fileBuffer });
|
||||
}
|
||||
|
||||
sendBinaryData('./path/to/your/file.png');
|
||||
```
|
||||
|
||||
### Securing Your WebSocket Communication
|
||||
|
||||
@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.
|
||||
|
||||
### Advanced Usage
|
||||
|
||||
#### Mesh Networking
|
||||
|
||||
@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.
|
||||
|
||||
#### Scaling with @push.rocks/smartsocket
|
||||
|
||||
To scale your WebSocket services, you can utilize load balancers and ensure your @push.rocks/smartsocket instances are stateless to allow for horizontal scaling.
|
||||
|
||||
### Conclusion
|
||||
|
||||
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.
|
||||
|
||||
For more detailed documentation, visit [the official @push.rocks/smartsocket GitLab repository](https://gitlab.com/pushrocks/smartsocket).
|
||||
|
||||
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.
|
||||
|
||||
Happy coding!
|
||||
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
**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
|
||||
|
||||
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.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
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.
|
||||
|
||||
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.
|
||||
|
@ -2,7 +2,7 @@
|
||||
import { expect, expectAsync, tap } from '@push.rocks/tapbundle';
|
||||
|
||||
import * as isohash from '@push.rocks/isohash';
|
||||
import * as smartexpress from '@apiglobal/typedserver';
|
||||
import * as smartexpress from '@api.global/typedserver';
|
||||
|
||||
import * as smartsocket from '../ts/index.js';
|
||||
|
||||
|
@ -1,8 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @pushrocks/commitinfo
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartsocket',
|
||||
version: '2.0.20',
|
||||
description: 'easy and secure websocket communication'
|
||||
version: '2.1.0',
|
||||
description: 'Provides easy and secure websocket communication mechanisms, including server and client implementation, function call routing, connection management, and tagging.'
|
||||
}
|
||||
|
@ -5,3 +5,6 @@ export * from './smartsocket.classes.smartsocketclient.js';
|
||||
// export further classes and objects
|
||||
export * from './smartsocket.classes.socketfunction.js';
|
||||
export * from './smartsocket.classes.socketconnection.js';
|
||||
|
||||
// export types so they can be referred to
|
||||
export * from './interfaces/index.js';
|
@ -18,6 +18,9 @@ export interface ISmartsocketClientOptions {
|
||||
url: string;
|
||||
alias: string; // an alias makes it easier to identify this client in a multo client environment
|
||||
autoReconnect?: boolean;
|
||||
maxRetries?: number; // maximum number of reconnection attempts
|
||||
initialBackoffDelay?: number; // initial backoff delay in ms
|
||||
maxBackoffDelay?: number; // maximum backoff delay in ms
|
||||
}
|
||||
|
||||
export class SmartsocketClient {
|
||||
@ -32,6 +35,11 @@ export class SmartsocketClient {
|
||||
public serverUrl: string;
|
||||
public serverPort: number;
|
||||
public autoReconnect: boolean;
|
||||
public maxRetries: number;
|
||||
public initialBackoffDelay: number;
|
||||
public maxBackoffDelay: number;
|
||||
public currentRetryCount = 0;
|
||||
public currentBackoffDelay: number;
|
||||
|
||||
// status handling
|
||||
public eventSubject = new plugins.smartrx.rxjs.Subject<interfaces.TConnectionStatus>();
|
||||
@ -79,6 +87,10 @@ export class SmartsocketClient {
|
||||
this.serverUrl = optionsArg.url;
|
||||
this.serverPort = optionsArg.port;
|
||||
this.autoReconnect = optionsArg.autoReconnect;
|
||||
this.maxRetries = optionsArg.maxRetries ?? 100; // Default to 100 retries
|
||||
this.initialBackoffDelay = optionsArg.initialBackoffDelay ?? 1000; // Default to 1 second
|
||||
this.maxBackoffDelay = optionsArg.maxBackoffDelay ?? 60000; // Default to 1 minute
|
||||
this.currentBackoffDelay = this.initialBackoffDelay;
|
||||
}
|
||||
|
||||
public addSocketFunction(socketFunction: SocketFunction<any>) {
|
||||
@ -89,6 +101,10 @@ export class SmartsocketClient {
|
||||
* connect the client to the server
|
||||
*/
|
||||
public async connect() {
|
||||
// Reset retry counters on new connection attempt
|
||||
this.currentRetryCount = 0;
|
||||
this.currentBackoffDelay = this.initialBackoffDelay;
|
||||
|
||||
const done = plugins.smartpromise.defer();
|
||||
const smartenvInstance = new plugins.smartenv.Smartenv();
|
||||
const socketIoClient: any = await smartenvInstance.getEnvAwareModule({
|
||||
@ -216,8 +232,27 @@ export class SmartsocketClient {
|
||||
|
||||
if (this.autoReconnect && useAutoReconnectSetting && this.eventStatus !== 'connecting') {
|
||||
this.updateStatus('connecting');
|
||||
console.log('debounced reconnect!');
|
||||
await plugins.smartdelay.delayForRandom(10000, 20000);
|
||||
|
||||
// Check if we've exceeded the maximum number of retries
|
||||
if (this.currentRetryCount >= this.maxRetries) {
|
||||
logger.log('warn', `Maximum reconnection attempts (${this.maxRetries}) reached. Giving up.`);
|
||||
this.disconnectRunning = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Increment retry counter
|
||||
this.currentRetryCount++;
|
||||
|
||||
// Calculate backoff with jitter (±20% randomness)
|
||||
const jitter = this.currentBackoffDelay * 0.2 * (Math.random() * 2 - 1);
|
||||
const delay = Math.min(this.currentBackoffDelay + jitter, this.maxBackoffDelay);
|
||||
|
||||
logger.log('info', `Reconnect attempt ${this.currentRetryCount}/${this.maxRetries} in ${Math.round(delay)}ms`);
|
||||
|
||||
// Apply exponential backoff for next time (doubling with each attempt)
|
||||
this.currentBackoffDelay = Math.min(this.currentBackoffDelay * 2, this.maxBackoffDelay);
|
||||
|
||||
await plugins.smartdelay.delayFor(delay);
|
||||
this.disconnectRunning = false;
|
||||
await this.connect();
|
||||
} else {
|
||||
@ -230,6 +265,8 @@ export class SmartsocketClient {
|
||||
*/
|
||||
public async stop() {
|
||||
this.autoReconnect = false;
|
||||
this.currentRetryCount = 0;
|
||||
this.currentBackoffDelay = this.initialBackoffDelay;
|
||||
await this.disconnect();
|
||||
}
|
||||
|
||||
@ -262,5 +299,19 @@ export class SmartsocketClient {
|
||||
this.eventSubject.next(statusArg);
|
||||
}
|
||||
this.eventStatus = statusArg;
|
||||
|
||||
// Reset reconnection state when connection is successful
|
||||
if (statusArg === 'connected') {
|
||||
this.currentRetryCount = 0;
|
||||
this.currentBackoffDelay = this.initialBackoffDelay;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the reconnection state
|
||||
*/
|
||||
public resetReconnectionState() {
|
||||
this.currentRetryCount = 0;
|
||||
this.currentBackoffDelay = this.initialBackoffDelay;
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
// apiglobal scope
|
||||
import * as typedrequestInterfaces from '@apiglobal/typedrequest-interfaces';
|
||||
import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';
|
||||
|
||||
export { typedrequestInterfaces };
|
||||
|
||||
|
@ -5,7 +5,7 @@ import type * as https from 'https';
|
||||
export type { http, https };
|
||||
|
||||
// pushrocks scope
|
||||
import type * as typedserver from '@apiglobal/typedserver';
|
||||
import type * as typedserver from '@api.global/typedserver';
|
||||
|
||||
export type { typedserver };
|
||||
|
||||
|
@ -3,9 +3,12 @@
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"target": "ES2022",
|
||||
"module": "ES2022",
|
||||
"moduleResolution": "nodenext",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
}
|
||||
"verbatimModuleSyntax": true
|
||||
},
|
||||
"exclude": [
|
||||
"dist_*/**/*.d.ts"
|
||||
]
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user