Enhance README for @serve.zone/interfaces: improve structure, add features, and clarify installation instructions

This commit is contained in:
2025-08-18 03:16:28 +00:00
parent 7d4e766e9e
commit 23c9e3f678

View File

@@ -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 ```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. Typed contracts for API communication:
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.
```typescript ```typescript
import { IRequest_GetAllImages } from '@serve.zone/interfaces/requests/image'; import {
IRequest_GetAllImages,
IRequest_CreateCluster,
IRequest_DeployService
} from '@serve.zone/interfaces';
class ImageService { // Type-safe request
private cloudlyClient; const request: IRequest_GetAllImages['request'] = {
identity: userIdentity,
constructor(cloudlyClient: CloudlyApiClient) { filters: {
this.cloudlyClient = cloudlyClient; tag: 'production'
} }
};
public async fetchAllImages() { // Type-safe response
const request: IRequest_GetAllImages['request'] = { const response: IRequest_GetAllImages['response'] = {
identity: this.cloudlyClient.identity, 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 Core data structures for Cloudly entities:
Logging is a crucial aspect of cloud applications. The module provides interfaces to assist in integrating logging systems like `@push.rocks/smartlog-interfaces`.
```typescript ```typescript
import { ILogger, ILogConfig } from '@push.rocks/smartlog-interfaces'; import {
ICluster,
IService,
IImage,
ISecret,
IServer
} from '@serve.zone/interfaces';
class LoggerService { // Define a service
private logger: ILogger; const service: IService = {
id: 'service-123',
constructor(logConfig: ILogConfig) { data: {
this.logger = new SmartLogger(logConfig); name: 'api-service',
imageId: 'image-456',
imageVersion: '2.0.0',
environment: {
NODE_ENV: 'production'
},
scaleFactor: 3,
balancingStrategy: 'round-robin',
ports: {
web: 80,
metrics: 9090
},
domains: [
{ name: 'api.example.com' }
],
deploymentIds: [],
deploymentDirectiveIds: []
} }
};
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. ### 🔐 Authentication & Identity
#### 3. Container Service Management Identity management interfaces:
Managing containers, particularly when dealing with microservices, can be complex, but interfaces like `IService`, `ICluster`, and `IServer` aid in structuring container service management.
```typescript ```typescript
import { IService } from '@serve.zone/interfaces/data/service'; import {
IIdentity,
IServiceToken,
IPermission
} from '@serve.zone/interfaces';
function defineService(): IService { const identity: IIdentity = {
return { id: 'user-789',
id: 'unique-service-id', name: 'service-account',
data: { type: 'service',
name: 'my-container-service', permissions: ['cluster:read', 'service:write'],
imageId: 'unique-image-id', tokenHash: 'hashed-token',
imageVersion: '1.0.0', metadata: {
environment: { KEY: 'VALUE' }, createdAt: new Date(),
secretBundleId: 'bundle-id', lastAccess: new Date()
scaleFactor: 2, }
balancingStrategy: 'round-robin', };
ports: { web: 80 },
domains: [{ name: 'example.com' }],
deploymentIds: [],
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. ### 🌐 Network Configuration
#### 4. Network Configuration and Routing Networking and routing interfaces:
Networking is integral to cloud-native applications. Interfaces in `@serve.zone/interfaces` help shape network interaction patterns.
```typescript ```typescript
import { IReverseProxyConfig } from '@serve.zone/interfaces/data/traffic'; import {
IReverseProxyConfig,
IDomainConfig,
ILoadBalancerConfig
} from '@serve.zone/interfaces';
const proxyConfig: IReverseProxyConfig = { const proxyConfig: IReverseProxyConfig = {
domain: 'example.com', domain: 'app.example.com',
path: '/', path: '/api',
serviceAddress: 'http://service:8080', serviceAddress: 'http://api-service:3000',
ssl: true, ssl: true,
headers: {
'X-Real-IP': '$remote_addr'
}
}; };
function configureProxy() {
// Logic to apply the proxyConfig, potentially using Typedi, Smartclient, or similar libraries.
}
``` ```
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 Observability interfaces:
#### Monitoring and Metrics Collection
For observability, you can track system metrics using `IServerMetrics` or cluster status interfaces.
```typescript ```typescript
import { IServerMetrics } from '@serve.zone/interfaces/data/server'; import {
IServerMetrics,
IServiceMetrics,
IClusterHealth
} from '@serve.zone/interfaces';
function reportMetrics(metrics: IServerMetrics) { const metrics: IServerMetrics = {
console.log(`CPU Usage: ${metrics.cpuUsageInPercent}%`); serverId: 'server-001',
console.log(`Memory Usage: ${metrics.memoryUsageinMB}MB`); cpuUsageInPercent: 65,
} memoryUsageinMB: 3072,
memoryAvailableInMB: 8192,
const sampleMetrics: IServerMetrics = { diskUsageInPercent: 40,
serverId: 'server-123', networkInMbps: 100,
cpuUsageInPercent: 45, networkOutMbps: 150,
memoryUsageinMB: 2048, containerCount: 12,
memoryAvailableInMB: 4096, containerMetrics: [...]
containerCount: 10,
containerMetrics: [],
}; };
reportMetrics(sampleMetrics);
``` ```
Implementing such metrics tracking provides insight into performance bottlenecks and helps strategize scaling decisions. ### 🔒 Secret Management
#### Certificate Management Security and credential interfaces:
To handle SSL certificates programmatically, utilize interfaces such as `IRequest_Any_Cloudly_GetCertificateForDomain`.
```typescript ```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 secretGroup: ISecretGroup = {
const request: IRequest_Any_Cloudly_GetCertificateForDomain['request'] = { id: 'secrets-123',
identity: cloudlyClient.identity, name: 'database-credentials',
domainName: domainName, secrets: [
type: 'ssl' {
}; key: 'DB_HOST',
value: 'encrypted-value',
encrypted: true
},
{
key: 'DB_PASSWORD',
value: 'encrypted-value',
encrypted: true
}
],
metadata: {
environment: 'production',
service: 'api'
}
};
```
return await cloudlyClient.typedsocketClient.fireTypedRequest<IRequest_Any_Cloudly_GetCertificateForDomain>(request); ## 📚 Common Usage Patterns
### Creating Type-Safe API Clients
```typescript
import {
IRequest_CreateService,
IService
} from '@serve.zone/interfaces';
class ServiceClient {
async createService(
serviceData: IService['data']
): Promise<IService> {
const request: IRequest_CreateService['request'] = {
identity: this.identity,
serviceData
};
const response = await this.client.send<IRequest_CreateService>(
'createService',
request
);
return response.service;
}
} }
``` ```
Managing certificates dynamically via typed requests simplifies deployment and automates the security dimensions of your applications. ### Validating Incoming Data
#### Integrating with External Messaging Services
Use `IRequest_SendEmail` to integrate platform services for sending emails:
```typescript ```typescript
import { IRequest_SendEmail } from '@serve.zone/interfaces/platformservice/mta'; import { ICluster } from '@serve.zone/interfaces';
import { validateType } from 'your-validation-library';
async function sendNotification(emailClient: any) { function validateClusterData(data: unknown): ICluster {
const emailRequest: IRequest_SendEmail['request'] = { if (!validateType<ICluster>(data)) {
title: 'Welcome to ServeZone!', throw new Error('Invalid cluster data');
from: 'service@company.com', }
to: 'user@example.com', return data;
body: '<h1>Congratulations</h1><p>Your account has been created successfully.</p>',
};
await emailClient.sendEmail(emailRequest);
} }
``` ```
This approach demonstrates abstracting the email sending functionality using typed interfaces, contributing to code consistency and robustness. ### Building Configuration Objects
### Conclusion ```typescript
import {
ICloudlyConfig,
IMongoDescriptor
} from '@serve.zone/interfaces';
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. 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!
}
};
```
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. ## 🎯 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 ## License and Legal Information