Enhance README for @serve.zone/interfaces: improve structure, add features, and clarify installation instructions
This commit is contained in:
@@ -1,207 +1,375 @@
|
||||
# @serve.zone/interfaces
|
||||
# @serve.zone/interfaces 📋
|
||||
|
||||
interfaces for working with containers
|
||||
**TypeScript interfaces for the Cloudly ecosystem.** Type-safe contracts for multi-cloud infrastructure management.
|
||||
|
||||
## Install
|
||||
## 🎯 What is @serve.zone/interfaces?
|
||||
|
||||
To install `@serve.zone/interfaces`, run the following command in your terminal:
|
||||
This package provides the complete set of TypeScript interfaces that power the Cloudly platform. It ensures type safety and consistency across all components - from API requests to data models, from service definitions to infrastructure configurations.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
- **🔒 Type Safety** - Comprehensive TypeScript interfaces for all Cloudly operations
|
||||
- **📦 Modular Structure** - Organized by domain for easy navigation
|
||||
- **🔄 Version Compatibility** - Interfaces versioned with the platform
|
||||
- **📚 Well Documented** - Each interface includes JSDoc comments
|
||||
- **🎭 Multi-Purpose** - Used by API clients, CLI tools, and web interfaces
|
||||
- **✅ Validation Ready** - Compatible with runtime type checking libraries
|
||||
|
||||
## 🚀 Installation
|
||||
|
||||
```bash
|
||||
npm install @serve.zone/interfaces --save
|
||||
pnpm add @serve.zone/interfaces
|
||||
```
|
||||
|
||||
This will add `@serve.zone/interfaces` to your project's dependencies, allowing you to import and use various predefined interfaces that facilitate container operations and interactions within the ServeZone ecosystem.
|
||||
## 🏗️ Interface Categories
|
||||
|
||||
## Usage
|
||||
### 📡 Request/Response Interfaces
|
||||
|
||||
The `@serve.zone/interfaces` module provides a robust set of TypeScript interfaces designed to standardize interaction with various services and components in a cloud-native environment. The interfaces are targeted at simplifying the integration process with container orchestration, network configurations, logging, and service definitions. The module is particularly useful if you're working on infrastructure or service orchestration solutions using Node.js and TypeScript.
|
||||
|
||||
This document guides you through a comprehensive use case scenario of `@serve.zone/interfaces`. We will cover how to effectively utilize these interfaces to set up cloud services, manage application configurations, and handle system-related communications. This tutorial will explore various feature sets within the module, focusing on real-world implementations and practical coding strategies.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Before diving in, make sure to satisfy the following prerequisites:
|
||||
|
||||
- **Node.js**: Ensure you have Node.js installed (preferably the latest LTS version).
|
||||
|
||||
- **TypeScript**: Your environment should support TypeScript, as this module leverages strong typing offered by TypeScript.
|
||||
|
||||
- **Cloud Account Access**: Some of the interfaces interact with live cloud services; thus, ensure you have necessary credentials (like API tokens) available for testing or integration.
|
||||
|
||||
### Core Interfaces and Scenarios
|
||||
|
||||
#### 1. Handling Typed Requests
|
||||
|
||||
One fundamental aspect is defining typed requests, which standardizes API call definitions across different microservices or components. The module offers interfaces such as `IRequest_GetAllImages`, `IRequest_CreateCluster`, that you can extend or implement within your service logic to ensure strong typing and consistency.
|
||||
Typed contracts for API communication:
|
||||
|
||||
```typescript
|
||||
import { IRequest_GetAllImages } from '@serve.zone/interfaces/requests/image';
|
||||
import {
|
||||
IRequest_GetAllImages,
|
||||
IRequest_CreateCluster,
|
||||
IRequest_DeployService
|
||||
} from '@serve.zone/interfaces';
|
||||
|
||||
class ImageService {
|
||||
private cloudlyClient;
|
||||
|
||||
constructor(cloudlyClient: CloudlyApiClient) {
|
||||
this.cloudlyClient = cloudlyClient;
|
||||
}
|
||||
|
||||
public async fetchAllImages() {
|
||||
// Type-safe request
|
||||
const request: IRequest_GetAllImages['request'] = {
|
||||
identity: this.cloudlyClient.identity,
|
||||
identity: userIdentity,
|
||||
filters: {
|
||||
tag: 'production'
|
||||
}
|
||||
};
|
||||
|
||||
// Type-safe response
|
||||
const response: IRequest_GetAllImages['response'] = {
|
||||
images: [...]
|
||||
};
|
||||
const response = await this.cloudlyClient.typedsocketClient.fireTypedRequest<IRequest_GetAllImages>(request);
|
||||
return response.images;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In the above code, we structured a simple function to retrieve all images from a service, assuming the `cloudlyClient` is your authenticated API client. The typed request interface ensures that both the request and response align with the expected types.
|
||||
### 📦 Data Models
|
||||
|
||||
#### 2. Logging and Smart Logging Interfaces
|
||||
|
||||
Logging is a crucial aspect of cloud applications. The module provides interfaces to assist in integrating logging systems like `@push.rocks/smartlog-interfaces`.
|
||||
Core data structures for Cloudly entities:
|
||||
|
||||
```typescript
|
||||
import { ILogger, ILogConfig } from '@push.rocks/smartlog-interfaces';
|
||||
import {
|
||||
ICluster,
|
||||
IService,
|
||||
IImage,
|
||||
ISecret,
|
||||
IServer
|
||||
} from '@serve.zone/interfaces';
|
||||
|
||||
class LoggerService {
|
||||
private logger: ILogger;
|
||||
|
||||
constructor(logConfig: ILogConfig) {
|
||||
this.logger = new SmartLogger(logConfig);
|
||||
}
|
||||
|
||||
public logMessage(logPackage: ILogPackage) {
|
||||
this.logger.log(logPackage);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This illustrates a logger service utilizing `ILogConfig` to configure and initiate a logging mechanism. You can log structured data using `logPackage`, thus enhancing traceability and debugging efficiency.
|
||||
|
||||
#### 3. Container Service Management
|
||||
|
||||
Managing containers, particularly when dealing with microservices, can be complex, but interfaces like `IService`, `ICluster`, and `IServer` aid in structuring container service management.
|
||||
|
||||
```typescript
|
||||
import { IService } from '@serve.zone/interfaces/data/service';
|
||||
|
||||
function defineService(): IService {
|
||||
return {
|
||||
id: 'unique-service-id',
|
||||
// Define a service
|
||||
const service: IService = {
|
||||
id: 'service-123',
|
||||
data: {
|
||||
name: 'my-container-service',
|
||||
imageId: 'unique-image-id',
|
||||
imageVersion: '1.0.0',
|
||||
environment: { KEY: 'VALUE' },
|
||||
secretBundleId: 'bundle-id',
|
||||
scaleFactor: 2,
|
||||
name: 'api-service',
|
||||
imageId: 'image-456',
|
||||
imageVersion: '2.0.0',
|
||||
environment: {
|
||||
NODE_ENV: 'production'
|
||||
},
|
||||
scaleFactor: 3,
|
||||
balancingStrategy: 'round-robin',
|
||||
ports: { web: 80 },
|
||||
domains: [{ name: 'example.com' }],
|
||||
ports: {
|
||||
web: 80,
|
||||
metrics: 9090
|
||||
},
|
||||
domains: [
|
||||
{ name: 'api.example.com' }
|
||||
],
|
||||
deploymentIds: [],
|
||||
deploymentDirectiveIds: [],
|
||||
deploymentDirectiveIds: []
|
||||
}
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
In the example, a service definition is drafted, encapsulating critical service metadata, including its environment variables, domain configuration, and load balancing strategy. Adhering to `IService` ensures that all necessary service data is encapsulated correctly.
|
||||
### 🔐 Authentication & Identity
|
||||
|
||||
#### 4. Network Configuration and Routing
|
||||
|
||||
Networking is integral to cloud-native applications. Interfaces in `@serve.zone/interfaces` help shape network interaction patterns.
|
||||
Identity management interfaces:
|
||||
|
||||
```typescript
|
||||
import { IReverseProxyConfig } from '@serve.zone/interfaces/data/traffic';
|
||||
import {
|
||||
IIdentity,
|
||||
IServiceToken,
|
||||
IPermission
|
||||
} from '@serve.zone/interfaces';
|
||||
|
||||
const identity: IIdentity = {
|
||||
id: 'user-789',
|
||||
name: 'service-account',
|
||||
type: 'service',
|
||||
permissions: ['cluster:read', 'service:write'],
|
||||
tokenHash: 'hashed-token',
|
||||
metadata: {
|
||||
createdAt: new Date(),
|
||||
lastAccess: new Date()
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 🌐 Network Configuration
|
||||
|
||||
Networking and routing interfaces:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
IReverseProxyConfig,
|
||||
IDomainConfig,
|
||||
ILoadBalancerConfig
|
||||
} from '@serve.zone/interfaces';
|
||||
|
||||
const proxyConfig: IReverseProxyConfig = {
|
||||
domain: 'example.com',
|
||||
path: '/',
|
||||
serviceAddress: 'http://service:8080',
|
||||
domain: 'app.example.com',
|
||||
path: '/api',
|
||||
serviceAddress: 'http://api-service:3000',
|
||||
ssl: true,
|
||||
};
|
||||
|
||||
function configureProxy() {
|
||||
// Logic to apply the proxyConfig, potentially using Typedi, Smartclient, or similar libraries.
|
||||
headers: {
|
||||
'X-Real-IP': '$remote_addr'
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Here, `IReverseProxyConfig` is used to define a reverse proxy for a service. Such configurations are necessary for routing external requests into internal services securely.
|
||||
### 📊 Monitoring & Metrics
|
||||
|
||||
### Advanced Interface Utilization
|
||||
|
||||
#### Monitoring and Metrics Collection
|
||||
|
||||
For observability, you can track system metrics using `IServerMetrics` or cluster status interfaces.
|
||||
Observability interfaces:
|
||||
|
||||
```typescript
|
||||
import { IServerMetrics } from '@serve.zone/interfaces/data/server';
|
||||
import {
|
||||
IServerMetrics,
|
||||
IServiceMetrics,
|
||||
IClusterHealth
|
||||
} from '@serve.zone/interfaces';
|
||||
|
||||
function reportMetrics(metrics: IServerMetrics) {
|
||||
console.log(`CPU Usage: ${metrics.cpuUsageInPercent}%`);
|
||||
console.log(`Memory Usage: ${metrics.memoryUsageinMB}MB`);
|
||||
}
|
||||
|
||||
const sampleMetrics: IServerMetrics = {
|
||||
serverId: 'server-123',
|
||||
cpuUsageInPercent: 45,
|
||||
memoryUsageinMB: 2048,
|
||||
memoryAvailableInMB: 4096,
|
||||
containerCount: 10,
|
||||
containerMetrics: [],
|
||||
const metrics: IServerMetrics = {
|
||||
serverId: 'server-001',
|
||||
cpuUsageInPercent: 65,
|
||||
memoryUsageinMB: 3072,
|
||||
memoryAvailableInMB: 8192,
|
||||
diskUsageInPercent: 40,
|
||||
networkInMbps: 100,
|
||||
networkOutMbps: 150,
|
||||
containerCount: 12,
|
||||
containerMetrics: [...]
|
||||
};
|
||||
|
||||
reportMetrics(sampleMetrics);
|
||||
```
|
||||
|
||||
Implementing such metrics tracking provides insight into performance bottlenecks and helps strategize scaling decisions.
|
||||
### 🔒 Secret Management
|
||||
|
||||
#### Certificate Management
|
||||
|
||||
To handle SSL certificates programmatically, utilize interfaces such as `IRequest_Any_Cloudly_GetCertificateForDomain`.
|
||||
Security and credential interfaces:
|
||||
|
||||
```typescript
|
||||
import { IRequest_Any_Cloudly_GetCertificateForDomain } from '@serve.zone/interfaces/requests/certificate';
|
||||
import {
|
||||
ISecretGroup,
|
||||
ISecretBundle,
|
||||
IEncryptedData
|
||||
} from '@serve.zone/interfaces';
|
||||
|
||||
async function fetchCertificate(cloudlyClient: CloudlyApiClient, domainName: string) {
|
||||
const request: IRequest_Any_Cloudly_GetCertificateForDomain['request'] = {
|
||||
identity: cloudlyClient.identity,
|
||||
domainName: domainName,
|
||||
type: 'ssl'
|
||||
};
|
||||
|
||||
return await cloudlyClient.typedsocketClient.fireTypedRequest<IRequest_Any_Cloudly_GetCertificateForDomain>(request);
|
||||
const secretGroup: ISecretGroup = {
|
||||
id: 'secrets-123',
|
||||
name: 'database-credentials',
|
||||
secrets: [
|
||||
{
|
||||
key: 'DB_HOST',
|
||||
value: 'encrypted-value',
|
||||
encrypted: true
|
||||
},
|
||||
{
|
||||
key: 'DB_PASSWORD',
|
||||
value: 'encrypted-value',
|
||||
encrypted: true
|
||||
}
|
||||
],
|
||||
metadata: {
|
||||
environment: 'production',
|
||||
service: 'api'
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Managing certificates dynamically via typed requests simplifies deployment and automates the security dimensions of your applications.
|
||||
## 📚 Common Usage Patterns
|
||||
|
||||
#### Integrating with External Messaging Services
|
||||
|
||||
Use `IRequest_SendEmail` to integrate platform services for sending emails:
|
||||
### Creating Type-Safe API Clients
|
||||
|
||||
```typescript
|
||||
import { IRequest_SendEmail } from '@serve.zone/interfaces/platformservice/mta';
|
||||
import {
|
||||
IRequest_CreateService,
|
||||
IService
|
||||
} from '@serve.zone/interfaces';
|
||||
|
||||
async function sendNotification(emailClient: any) {
|
||||
const emailRequest: IRequest_SendEmail['request'] = {
|
||||
title: 'Welcome to ServeZone!',
|
||||
from: 'service@company.com',
|
||||
to: 'user@example.com',
|
||||
body: '<h1>Congratulations</h1><p>Your account has been created successfully.</p>',
|
||||
class ServiceClient {
|
||||
async createService(
|
||||
serviceData: IService['data']
|
||||
): Promise<IService> {
|
||||
const request: IRequest_CreateService['request'] = {
|
||||
identity: this.identity,
|
||||
serviceData
|
||||
};
|
||||
|
||||
await emailClient.sendEmail(emailRequest);
|
||||
const response = await this.client.send<IRequest_CreateService>(
|
||||
'createService',
|
||||
request
|
||||
);
|
||||
|
||||
return response.service;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This approach demonstrates abstracting the email sending functionality using typed interfaces, contributing to code consistency and robustness.
|
||||
### Validating Incoming Data
|
||||
|
||||
### Conclusion
|
||||
```typescript
|
||||
import { ICluster } from '@serve.zone/interfaces';
|
||||
import { validateType } from 'your-validation-library';
|
||||
|
||||
The `@serve.zone/interfaces` module equips developers with a set of interfaces tailored for managing containers, orchestrating cloud services, and handling system interactions seamlessly. By applying these interfaces, projects can achieve coherence, reduce coupling, and simplify the integration process across various service domains.
|
||||
function validateClusterData(data: unknown): ICluster {
|
||||
if (!validateType<ICluster>(data)) {
|
||||
throw new Error('Invalid cluster data');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
```
|
||||
|
||||
Focusing on practical applications, try extending these interfaces to suit additional requirements in your projects. Engage actively with the module community, or contribute new ideas to enhance the breadth and depth of this interface library. Explore the integration patterns showcased here and contribute toward a sophisticated cloud-native development framework.
|
||||
### Building Configuration Objects
|
||||
|
||||
```typescript
|
||||
import {
|
||||
ICloudlyConfig,
|
||||
IMongoDescriptor
|
||||
} from '@serve.zone/interfaces';
|
||||
|
||||
const config: ICloudlyConfig = {
|
||||
cfToken: process.env.CF_TOKEN!,
|
||||
hetznerToken: process.env.HETZNER_TOKEN!,
|
||||
environment: 'production',
|
||||
letsEncryptEmail: 'certs@example.com',
|
||||
publicUrl: 'cloudly.example.com',
|
||||
publicPort: 443,
|
||||
mongoDescriptor: {
|
||||
mongoDbUrl: process.env.MONGO_URL!,
|
||||
mongoDbName: 'cloudly',
|
||||
mongoDbUser: process.env.MONGO_USER!,
|
||||
mongoDbPass: process.env.MONGO_PASS!
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## 🎯 Advanced Features
|
||||
|
||||
### Generic Request Handler
|
||||
|
||||
```typescript
|
||||
import { ITypedRequest } from '@serve.zone/interfaces';
|
||||
|
||||
class RequestHandler {
|
||||
async handle<T extends ITypedRequest>(
|
||||
request: T['request']
|
||||
): Promise<T['response']> {
|
||||
// Type-safe request handling
|
||||
return this.processRequest(request);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Discriminated Unions
|
||||
|
||||
```typescript
|
||||
import { IDeploymentStatus } from '@serve.zone/interfaces';
|
||||
|
||||
function handleStatus(status: IDeploymentStatus) {
|
||||
switch (status.type) {
|
||||
case 'pending':
|
||||
console.log('Deployment pending...');
|
||||
break;
|
||||
case 'running':
|
||||
console.log(`Running on ${status.serverId}`);
|
||||
break;
|
||||
case 'failed':
|
||||
console.log(`Failed: ${status.error}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Extending Interfaces
|
||||
|
||||
```typescript
|
||||
import { IService } from '@serve.zone/interfaces';
|
||||
|
||||
interface IExtendedService extends IService {
|
||||
customMetadata: {
|
||||
team: string;
|
||||
costCenter: string;
|
||||
sla: 'standard' | 'premium';
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
## 🔄 Version Compatibility
|
||||
|
||||
| @serve.zone/interfaces | @serve.zone/cloudly | @serve.zone/api | @serve.zone/cli |
|
||||
|------------------------|---------------------|-----------------|-----------------|
|
||||
| 5.x | 5.x | 5.x | 5.x |
|
||||
| 4.x | 4.x | 4.x | 4.x |
|
||||
| 3.x | 3.x | 3.x | 3.x |
|
||||
|
||||
## 📖 Interface Documentation
|
||||
|
||||
All interfaces include comprehensive JSDoc comments:
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* Represents a cluster configuration
|
||||
* @interface ICluster
|
||||
*/
|
||||
export interface ICluster {
|
||||
/**
|
||||
* Unique identifier for the cluster
|
||||
* @type {string}
|
||||
*/
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* Cluster configuration data
|
||||
* @type {IClusterData}
|
||||
*/
|
||||
data: IClusterData;
|
||||
}
|
||||
```
|
||||
|
||||
## 🛠️ Development Tips
|
||||
|
||||
### Import Organization
|
||||
|
||||
```typescript
|
||||
// Group imports by category
|
||||
import {
|
||||
// Data models
|
||||
ICluster,
|
||||
IService,
|
||||
IImage,
|
||||
|
||||
// Requests
|
||||
IRequest_CreateCluster,
|
||||
IRequest_DeployService,
|
||||
|
||||
// Configuration
|
||||
ICloudlyConfig,
|
||||
IReverseProxyConfig
|
||||
} from '@serve.zone/interfaces';
|
||||
```
|
||||
|
||||
### Type Guards
|
||||
|
||||
```typescript
|
||||
import { IService, ICluster } from '@serve.zone/interfaces';
|
||||
|
||||
function isService(entity: IService | ICluster): entity is IService {
|
||||
return 'imageId' in entity.data;
|
||||
}
|
||||
```
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
|
Reference in New Issue
Block a user