Skip to content

feat: Add Backend Platform Websocket service #6007

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions packages/backend-platform/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

## [1.0.0] - Initial Release

### Added

- Initial release of @metamask/backend-platform
21 changes: 21 additions & 0 deletions packages/backend-platform/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) MetaMask

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
157 changes: 157 additions & 0 deletions packages/backend-platform/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
# `@metamask/backend-platform`

Backend platform utilities and services for MetaMask.

## Installation

`yarn add @metamask/backend-platform`

or

`npm install @metamask/backend-platform`

## Features

- **WebSocket Service**: Robust WebSocket client with automatic reconnection, circuit breaker pattern, and service degradation detection
- **Type-safe utilities**: Common types and utility functions for backend operations
- **Service patterns**: Following MetaMask's service architecture guidelines

## Usage

### WebSocket Service

```typescript
import { WebSocketService, WebSocketState } from '@metamask/backend-platform';

// Create a WebSocket service instance
const websocketService = new WebSocketService({
url: 'wss://your-internal-backend.com/ws',
environment: 'production',
authToken: 'your-auth-token',
connectionTimeout: 15000,
pingInterval: 30000,
maxReconnectAttempts: 5,
policyOptions: {
maxRetries: 3,
maxConsecutiveFailures: 5,
circuitBreakDuration: 60000,
degradedThreshold: 3000,
},
});

// Set up event handlers
websocketService.on('connected', () => {
console.log('Connected to WebSocket server');
});

websocketService.on('message', (message) => {
console.log('Received message:', message);
});

websocketService.on('error', (error) => {
console.error('WebSocket error:', error);
});

// Handle service policy events (recommended approach)
websocketService.onBreak((data) => {
console.warn('Circuit breaker triggered:', data);
});

websocketService.onDegraded(() => {
console.warn('Service is degraded');
});

websocketService.onRetry((data) => {
console.log('Retrying connection:', data);
});

// Deprecated approach (still supported for backward compatibility)
const websocketServiceDeprecated = new WebSocketService({
url: 'wss://your-internal-backend.com/ws',
environment: 'production',
// @deprecated - use onBreak() method instead
onBreak: () => console.warn('Circuit breaker triggered'),
// @deprecated - use onDegraded() method instead
onDegraded: () => console.warn('Service is degraded'),
});

// Connect and send messages
async function example() {
try {
await websocketService.connect();

const response = await websocketService.send({
type: 'getUserAccount',
payload: { userId: 'user123' },
});

console.log('Response:', response);
} catch (error) {
console.error('Error:', error);
}
}
```

### Utility Functions

```typescript
import {
createSuccessResponse,
createErrorResponse,
isValidEnvironment
} from '@metamask/backend-platform';

// Create standardized responses
const success = createSuccessResponse({ user: 'data' });
const error = createErrorResponse('Something went wrong');

// Validate environment strings
if (isValidEnvironment(process.env.NODE_ENV)) {
console.log('Valid environment');
}
```

### Types

```typescript
import type {
BackendConfig,
BackendResponse,
WebSocketServiceOptions,
WebSocketMessage
} from '@metamask/backend-platform';

const config: BackendConfig = {
environment: 'development',
debug: true,
};

const response: BackendResponse<string> = {
success: true,
data: 'Hello world',
timestamp: Date.now(),
};
```

## Architecture

This package follows MetaMask's service architecture patterns:

- **Service Policy Integration**: Uses `@metamask/controller-utils` for retry logic, circuit breaker pattern, and service degradation detection
- **Event-driven Architecture**: WebSocket service implements an event emitter pattern for handling connection states and messages
- **Type Safety**: Comprehensive TypeScript types for all service interactions
- **Error Handling**: Robust error handling with automatic retries and fallback mechanisms

## WebSocket Service Features

- **Automatic Reconnection**: Configurable reconnection attempts with exponential backoff
- **Circuit Breaker**: Prevents cascading failures by temporarily stopping requests when service is down
- **Service Degradation Detection**: Monitors service performance and triggers callbacks when degraded
- **Authentication**: Built-in support for token-based authentication
- **Message Correlation**: Automatic correlation of request/response messages
- **Ping/Pong**: Configurable keep-alive mechanism
- **Connection State Management**: Comprehensive state tracking and event emission

## API Documentation

For detailed API documentation, please visit [our TypeDoc page](https://metamask.github.io/core/modules/_metamask_backend_platform.html).
30 changes: 30 additions & 0 deletions packages/backend-platform/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* For a detailed explanation regarding each configuration property and type check, visit:
* https://jestjs.io/docs/configuration
*/

const merge = require('deepmerge');
const path = require('path');

const baseConfig = require('../../tests/jest.config.packages');

const displayName = path.basename(__dirname);

module.exports = merge(baseConfig, {
// The display name when running multiple projects
displayName,

// An object that configures minimum threshold enforcement for coverage results
coverageThreshold: {
global: {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},

// We rely on `setupFiles` rather than `setupFilesAfterEnv` since we're not
// testing with jsdom.
setupFiles: ['<rootDir>/../../tests/setup.js'],
});
71 changes: 71 additions & 0 deletions packages/backend-platform/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
{
"name": "@metamask/backend-platform",
"version": "1.0.0",
"description": "Backend platform utilities and services for MetaMask",
"keywords": [
"MetaMask",
"Ethereum",
"Backend",
"Platform"
],
"homepage": "https://github.com/MetaMask/core/tree/main/packages/backend-platform#readme",
"bugs": {
"url": "https://github.com/MetaMask/core/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/MetaMask/core.git"
},
"license": "MIT",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./package.json": "./package.json"
},
"main": "./dist/index.cjs",
"types": "./dist/index.d.cts",
"files": [
"dist/"
],
"scripts": {
"build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
"build:docs": "typedoc",
"changelog:update": "../../scripts/update-changelog.sh @metamask/backend-platform",
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/backend-platform",
"publish:preview": "yarn npm publish --tag preview",
"since-latest-release": "../../scripts/since-latest-release.sh",
"test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
"test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
"test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
},
"dependencies": {
"@metamask/base-controller": "^8.0.1",
"@metamask/controller-utils": "^11.10.0",
"@metamask/utils": "^11.2.0"
},
"devDependencies": {
"@metamask/auto-changelog": "^3.4.4",
"@types/jest": "^27.4.1",
"jest": "^27.5.1",
"ts-jest": "^27.1.4",
"typedoc": "^0.24.8",
"typedoc-plugin-missing-exports": "^2.0.0",
"typescript": "~5.2.2"
},
"engines": {
"node": "^18.18 || >=20"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
}
26 changes: 26 additions & 0 deletions packages/backend-platform/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* @metamask/backend-platform
*
* Backend platform utilities and services for MetaMask.
*/

// Export types and utilities
// WebSocket Service - following MetaMask Data Services pattern
export type {
WebSocketServiceOptions,
WebSocketMessage,
WebSocketConnectionInfo,
WebSocketServiceActions,
WebSocketServiceConnectAction,
WebSocketServiceDisconnectAction,
WebSocketServiceSendMessageAction,
WebSocketServiceSendRequestAction,
WebSocketServiceGetConnectionInfoAction,
WebSocketServiceMessenger,
} from './websocket-service';

export {
WebSocketService,
WebSocketState,
WebSocketEventType,
} from './websocket-service';
43 changes: 43 additions & 0 deletions packages/backend-platform/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Common types for backend platform utilities.
*/

/**
* Base configuration interface for backend services.
*/
export interface BackendConfig {
/**
* The environment the backend is running in.
*/
environment: 'development' | 'staging' | 'production';

/**
* Optional debug mode flag.
*/
debug?: boolean;
}

/**
* Standard response format for backend operations.
*/
export interface BackendResponse<T = unknown> {
/**
* Whether the operation was successful.
*/
success: boolean;

/**
* The response data, if successful.
*/
data?: T;

/**
* Error message, if unsuccessful.
*/
error?: string;

/**
* Timestamp of the response.
*/
timestamp: number;
}
Loading