feat(transport): implement WebSocket-based isotransport client and server API with typed events and end-to-end tests
This commit is contained in:
@@ -1,103 +1,230 @@
|
||||
# @push.rocks/isotransport
|
||||
a bi-directional, multiplatform, best-effort transport
|
||||
|
||||
`@push.rocks/isotransport` is a tiny TypeScript transport layer for bi-directional, best-effort messaging over WebSockets. It gives Node.js and browser code the same simple connection API while keeping the actual transport intentionally lean: open a connection, send `string`, `ArrayBuffer`, or `Uint8Array` payloads, react to messages, and close cleanly.
|
||||
|
||||
## 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
|
||||
To install `@push.rocks/isotransport`, use the following command in your project directory:
|
||||
|
||||
```bash
|
||||
npm install @push.rocks/isotransport --save
|
||||
pnpm add @push.rocks/isotransport
|
||||
```
|
||||
|
||||
This will fetch and install the `isotransport` package and add it as a dependency to your project's `package.json` file.
|
||||
## What It Does
|
||||
|
||||
## Usage
|
||||
The `@push.rocks/isotransport` module is designed as a versatile transport layer that abstracts away the complexity of bi-directional communication across different platforms. Its goal is to provide a "best effort" transport, meaning it aims to optimize communication reliability and efficiency without guaranteeing message delivery under all circumstances.
|
||||
`isotransport` wraps WebSocket communication in three exported building blocks:
|
||||
|
||||
In the following sections, various aspects of using `@push.rocks/isotransport` are covered, including setting up a simple server-client connection, handling messages, and configuring the transport layer for different environments.
|
||||
- `IsotransportServer`: starts a WebSocket server in Node.js and emits typed connection objects.
|
||||
- `IsotransportClient`: connects to a WebSocket URL from Node.js or a browser-like runtime.
|
||||
- `IsotransportConnection`: represents one open peer connection and provides `send()`, `close()`, and typed event listeners.
|
||||
|
||||
### Basic Setup
|
||||
First, ensure that you are using TypeScript and have it configured in your project. `@push.rocks/isotransport` is developed with TypeScript in mind, offering type definitions out of the box for enhanced development experience.
|
||||
The module is deliberately best-effort. It does not queue messages, retry delivery, persist data, or add protocol framing. If the socket is closed, `send()` throws. This makes the library useful as a clean transport primitive that can sit below your own application protocol.
|
||||
|
||||
#### Importing
|
||||
Start by importing the necessary components from `@push.rocks/isotransport` in your TypeScript file:
|
||||
## Quick Start
|
||||
|
||||
```typescript
|
||||
import { IsotransportServer, IsotransportClient } from '@push.rocks/isotransport';
|
||||
```
|
||||
```ts
|
||||
import {
|
||||
IsotransportClient,
|
||||
IsotransportServer,
|
||||
type TIsotransportMessage,
|
||||
} from '@push.rocks/isotransport';
|
||||
|
||||
### Setting Up a Server
|
||||
To set up a server instance that listens for incoming connections, use the `IsotransportServer` class:
|
||||
|
||||
```typescript
|
||||
const transportServer = new IsotransportServer({
|
||||
port: 8080, // Specify the port on which the server should listen
|
||||
const server = new IsotransportServer({
|
||||
port: 8080,
|
||||
host: '127.0.0.1',
|
||||
});
|
||||
|
||||
// Start listening for connections
|
||||
transportServer.listen().then(() => {
|
||||
console.log('Server is listening for incoming connections...');
|
||||
});
|
||||
server.on('connection', (connection) => {
|
||||
console.log(`client connected: ${connection.id}`);
|
||||
|
||||
// Handling client connections
|
||||
transportServer.on('connection', (client) => {
|
||||
console.log('Client connected:', client.id);
|
||||
|
||||
client.on('message', (message) => {
|
||||
console.log('Message from client:', message);
|
||||
connection.on('message', (message: TIsotransportMessage) => {
|
||||
console.log('server received:', message);
|
||||
connection.send('pong');
|
||||
});
|
||||
|
||||
client.send('Welcome to isotransport server!');
|
||||
connection.on('close', () => {
|
||||
console.log(`client disconnected: ${connection.id}`);
|
||||
});
|
||||
});
|
||||
|
||||
await server.listen();
|
||||
|
||||
const client = new IsotransportClient({
|
||||
url: 'ws://127.0.0.1:8080',
|
||||
});
|
||||
|
||||
client.on('message', (message) => {
|
||||
console.log('client received:', message);
|
||||
});
|
||||
|
||||
await client.connect();
|
||||
client.send('ping');
|
||||
|
||||
// Later, during shutdown:
|
||||
client.close();
|
||||
await server.close();
|
||||
```
|
||||
|
||||
## Server API
|
||||
|
||||
Create a server with a port and optional host/path:
|
||||
|
||||
```ts
|
||||
const server = new IsotransportServer({
|
||||
port: 3000,
|
||||
host: '127.0.0.1',
|
||||
path: '/transport',
|
||||
});
|
||||
|
||||
await server.listen();
|
||||
```
|
||||
|
||||
`IsotransportServer` events:
|
||||
|
||||
- `connection`: emitted with an `IsotransportConnection` for every accepted WebSocket client.
|
||||
- `close`: emitted after `server.close()` finishes.
|
||||
- `error`: emitted when the underlying WebSocket server reports an error.
|
||||
|
||||
Server instances expose a `connections` set, so you can inspect or close currently connected peers:
|
||||
|
||||
```ts
|
||||
for (const connection of server.connections) {
|
||||
connection.send('server is shutting down');
|
||||
}
|
||||
|
||||
await server.close();
|
||||
```
|
||||
|
||||
## Client API
|
||||
|
||||
Create a client with a WebSocket URL and optional protocols:
|
||||
|
||||
```ts
|
||||
const client = new IsotransportClient({
|
||||
url: 'ws://127.0.0.1:3000/transport',
|
||||
protocols: ['my-protocol'],
|
||||
});
|
||||
|
||||
await client.connect();
|
||||
client.send('hello');
|
||||
```
|
||||
|
||||
`IsotransportClient` events:
|
||||
|
||||
- `open`: emitted with the active `IsotransportConnection` after the socket opens.
|
||||
- `message`: emitted for every received message.
|
||||
- `close`: emitted when the socket closes.
|
||||
- `error`: emitted when the socket reports an error.
|
||||
|
||||
In browsers, `IsotransportClient` uses `globalThis.WebSocket`. In Node.js, it falls back to the package's `ws` dependency.
|
||||
|
||||
## Connection API
|
||||
|
||||
Every connection supports:
|
||||
|
||||
```ts
|
||||
connection.on('message', (message) => {});
|
||||
connection.on('close', () => {});
|
||||
connection.on('error', (error) => {});
|
||||
|
||||
connection.send('text payload');
|
||||
connection.send(new Uint8Array([1, 2, 3]));
|
||||
connection.close();
|
||||
```
|
||||
|
||||
`connection.on(...)` returns an unsubscribe function:
|
||||
|
||||
```ts
|
||||
const stopListening = connection.on('message', (message) => {
|
||||
console.log(message);
|
||||
});
|
||||
|
||||
stopListening();
|
||||
```
|
||||
|
||||
Supported payloads are represented by `TIsotransportMessage`:
|
||||
|
||||
```ts
|
||||
type TIsotransportMessage = string | ArrayBuffer | Uint8Array;
|
||||
```
|
||||
|
||||
Text frames are delivered as strings. Binary frames are delivered as binary data from the underlying WebSocket implementation.
|
||||
|
||||
## Practical Notes
|
||||
|
||||
- Call `await server.listen()` before connecting clients.
|
||||
- Call `await client.connect()` before sending from the client.
|
||||
- `send()` throws if the connection is not open.
|
||||
- `server.close()` closes all tracked connections and stops the WebSocket server.
|
||||
- The library does not serialize objects; serialize JSON yourself if your protocol needs structured data.
|
||||
- The library does not provide authentication, authorization, heartbeats, retries, or message acknowledgements.
|
||||
|
||||
## JSON Messages
|
||||
|
||||
```ts
|
||||
connection.send(JSON.stringify({
|
||||
type: 'user.joined',
|
||||
payload: {
|
||||
userId: 'user-123',
|
||||
},
|
||||
}));
|
||||
|
||||
connection.on('message', (message) => {
|
||||
if (typeof message !== 'string') {
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(message) as {
|
||||
type: string;
|
||||
payload: unknown;
|
||||
};
|
||||
|
||||
console.log(parsed.type, parsed.payload);
|
||||
});
|
||||
```
|
||||
|
||||
### Setting Up a Client
|
||||
Setting up a client that connects to an isotransport server is straightforward with the `IsotransportClient` class:
|
||||
## Binary Messages
|
||||
|
||||
```typescript
|
||||
const transportClient = new IsotransportClient({
|
||||
url: 'ws://localhost:8080', // URL of the isotransport server
|
||||
});
|
||||
```ts
|
||||
const bytes = new Uint8Array([1, 2, 3, 4]);
|
||||
client.send(bytes);
|
||||
|
||||
// Connecting to the server
|
||||
transportClient.connect().then(() => {
|
||||
console.log('Connected to the server.');
|
||||
});
|
||||
|
||||
// Sending a message to the server
|
||||
transportClient.send('Hello, server!');
|
||||
|
||||
// Receiving messages from the server
|
||||
transportClient.on('message', (message) => {
|
||||
console.log('Message from server:', message);
|
||||
client.on('message', (message) => {
|
||||
if (message instanceof Uint8Array) {
|
||||
console.log('received bytes:', message.byteLength);
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Multiplatform Communication
|
||||
`@push.rocks/isotransport` shines in scenarios where communication needs to happen across different platforms, for example, between a Node.js server and a web client. The design of isotransport abstracts the underlying transport mechanisms (like WebSockets for web clients and TCP sockets for Node.js), offering a unified API for sending and receiving messages.
|
||||
## Development
|
||||
|
||||
### Advanced Configuration
|
||||
Isotransport provides hooks and configuration options for tweaking its behavior to fit specific use cases. For instance, you can configure retry strategies for message delivery, set custom serializers for message encoding/decoding, or integrate with custom logging solutions to monitor communication flows.
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm test
|
||||
pnpm build
|
||||
```
|
||||
|
||||
Due to the scope of this guide, these advanced topics are not covered in detail here. However, they are well-documented in the isotransport API documentation, offering comprehensive insights into enhancing the capabilities of your transport layer.
|
||||
|
||||
### Conclusion
|
||||
`@push.rocks/isotransport` is a powerful tool for creating reliable, efficient, and scalable communication layers in your application. By abstracting the complexities of bi-directional multiplatform communication, it allows developers to focus on building the core features of their applications. Whether you're developing a real-time chat application, a distributed microservices architecture, or any system that requires robust communication, isotransport provides the foundational elements needed to bring your project to life.
|
||||
Tests are written with `@git.zone/tstest` and exercise a real server/client message exchange over WebSockets.
|
||||
|
||||
## 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.
|
||||
|
||||
### 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
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District court Bremen HRB 35230 HB, Germany
|
||||
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.
|
||||
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.
|
||||
|
||||
Reference in New Issue
Block a user