Enhance documentation for @serve.zone/api and @serve.zone/cli
- Updated the README for @serve.zone/api to improve clarity and organization, adding sections for features, quick start, authentication, core operations, and advanced usage. - Improved the installation instructions and added examples for various operations including image management, cluster operations, and real-time updates. - Enhanced the @serve.zone/cli README with a focus on features, installation, quick start, core commands, and advanced usage. - Added detailed command examples for cluster management, service deployment, secret management, and DNS management. - Included sections for CI/CD integration and troubleshooting in both README files. - Improved formatting and added emojis for better readability and engagement.
This commit is contained in:
@@ -1,186 +1,290 @@
|
||||
# @serve.zone/api
|
||||
# @serve.zone/api 🔌
|
||||
|
||||
The `@serve.zone/api` module is a robust and versatile API client, designed to facilitate seamless communication with various cloud resources managed by the Cloudly platform. This API client extends a rich set of functionalities, offering developers a comprehensive and programmable interface for interacting with their multi-cloud infrastructure.
|
||||
**The powerful API client for Cloudly.** Connect your applications to multi-cloud infrastructure with type-safe, real-time communication.
|
||||
|
||||
## Install
|
||||
## 🎯 What is @serve.zone/api?
|
||||
|
||||
To install the `@serve.zone/api` package, execute the following command in your terminal:
|
||||
This is your programmatic gateway to the Cloudly platform. Built with TypeScript, it provides a robust, type-safe interface for managing cloud resources, orchestrating containers, and automating infrastructure operations.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
- **🔒 Type-Safe** - Full TypeScript support with comprehensive interfaces
|
||||
- **⚡ Real-Time** - WebSocket-based communication for instant updates
|
||||
- **🔑 Secure Authentication** - Token-based identity management
|
||||
- **📦 Resource Management** - Complete control over clusters, images, and services
|
||||
- **🎭 Multi-Identity** - Support for service accounts and user authentication
|
||||
- **🔄 Reactive Streams** - RxJS integration for event-driven programming
|
||||
|
||||
## 🚀 Installation
|
||||
|
||||
```bash
|
||||
npm install @serve.zone/api --save
|
||||
pnpm add @serve.zone/api
|
||||
```
|
||||
|
||||
This command will download the module and add it to your project's `package.json` dependencies, allowing you to utilize its capabilities within your application.
|
||||
|
||||
## Usage
|
||||
|
||||
The `@serve.zone/api` client is tailored to handle various operations within a multi-cloud environment efficiently. Throughout this section, we will explore the different features and use-cases of this API client, aiding you in leveraging its full potential.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Before integrating `@serve.zone/api` into your project, ensure the following prerequisites are satisfied:
|
||||
- You have Node.js installed on your system (preferably the latest Long-Term Support version).
|
||||
- You're utilizing a TypeScript-compatible environment for development.
|
||||
|
||||
### Establishing an API Client Instance
|
||||
|
||||
The cornerstone of using `@serve.zone/api` is initializing a `CloudlyApiClient` instance. It serves as the main point of interaction, enabling communication with underlying cloud infrastructures managed by Cloudly. Here's a basic setup guide:
|
||||
|
||||
```typescript
|
||||
import { CloudlyApiClient, TClientType } from '@serve.zone/api';
|
||||
|
||||
async function initializeClient() {
|
||||
const client = new CloudlyApiClient({
|
||||
registerAs: 'api' as TClientType,
|
||||
cloudlyUrl: 'https://yourcloudly.url:443'
|
||||
});
|
||||
|
||||
await client.start();
|
||||
return client;
|
||||
}
|
||||
|
||||
const cloudlyClient = await initializeClient();
|
||||
```
|
||||
|
||||
The above code initializes the `CloudlyApiClient` object, connecting your application to the configured Cloudly environment.
|
||||
|
||||
### Authentication and Identity Management
|
||||
|
||||
To execute operations via the API client, authenticated access is necessary. The most prevalent method for this is obtaining an identity token using a service token:
|
||||
## 🎬 Quick Start
|
||||
|
||||
```typescript
|
||||
import { CloudlyApiClient } from '@serve.zone/api';
|
||||
|
||||
async function authenticate(client: CloudlyApiClient, serviceToken: string) {
|
||||
const identity = await client.getIdentityByToken(serviceToken, {
|
||||
tagConnection: true,
|
||||
statefullIdentity: true
|
||||
});
|
||||
// Initialize the client
|
||||
const client = new CloudlyApiClient({
|
||||
registerAs: 'api',
|
||||
cloudlyUrl: 'https://cloudly.example.com:443'
|
||||
});
|
||||
|
||||
console.log(`Authenticated identity:`, identity);
|
||||
return identity;
|
||||
}
|
||||
// Start the connection
|
||||
await client.start();
|
||||
|
||||
const serviceToken = 'your_service_token';
|
||||
const identity = await authenticate(cloudlyClient, serviceToken);
|
||||
// Authenticate with a service token
|
||||
const identity = await client.getIdentityByToken('your-service-token', {
|
||||
tagConnection: true,
|
||||
statefullIdentity: true
|
||||
});
|
||||
|
||||
console.log('🎉 Connected as:', identity.name);
|
||||
```
|
||||
|
||||
In this function, the `getIdentityByToken` method authenticates using a service token and acquires an identity object that includes user details and security claims.
|
||||
## 🔐 Authentication
|
||||
|
||||
### Interacting with Cloudly Features
|
||||
|
||||
#### Image Management
|
||||
|
||||
Image management is one of the key features supported by the API Client. You can create, upload, and manage Docker images easily within your cloud ecosystem:
|
||||
### Service Token Authentication
|
||||
|
||||
```typescript
|
||||
async function manageImages(client: CloudlyApiClient, identity) {
|
||||
// Creating a new image
|
||||
const newImage = await client.images.createImage({
|
||||
name: 'my_new_image',
|
||||
description: 'A test image'
|
||||
});
|
||||
|
||||
console.log(`Created image:`, newImage);
|
||||
|
||||
// Uploading an image version
|
||||
const imageStream = fetchYourImageStreamHere(); // Provide the source image stream
|
||||
await newImage.pushImageVersion('1.0.0', imageStream);
|
||||
console.log('Image version uploaded successfully.');
|
||||
}
|
||||
|
||||
await manageImages(cloudlyClient, identity);
|
||||
|
||||
// Helper function for obtaining image stream (implement accordingly)
|
||||
function fetchYourImageStreamHere() {
|
||||
// Logic to fetch and return a readable stream for your image
|
||||
return new ReadableStream<Uint8Array>();
|
||||
}
|
||||
// Authenticate using a service token
|
||||
const identity = await client.getIdentityByToken(serviceToken, {
|
||||
tagConnection: true, // Tag this connection with the identity
|
||||
statefullIdentity: true // Maintain state across reconnections
|
||||
});
|
||||
```
|
||||
|
||||
In this example, the `manageImages` function underscores the typical workflow of creating an image entry within Cloudly and then proceeding to upload a specific version using the `pushImageVersion` method.
|
||||
|
||||
#### Cluster Configuration
|
||||
|
||||
Another powerful capability is managing clusters, which allows for orchestrating and configuring Docker Swarm clusters:
|
||||
### Identity Management
|
||||
|
||||
```typescript
|
||||
async function configureCluster(client: CloudlyApiClient, identity) {
|
||||
// Fetching cluster configuration
|
||||
const clusterConfig = await client.getClusterConfigFromCloudlyByIdentity(identity);
|
||||
console.log(`Cluster configuration retrieved:`, clusterConfig);
|
||||
}
|
||||
// Get current identity
|
||||
const currentIdentity = client.identity;
|
||||
|
||||
await configureCluster(cloudlyClient, identity);
|
||||
// Check permissions
|
||||
if (currentIdentity.permissions.includes('cluster:write')) {
|
||||
// Perform cluster operations
|
||||
}
|
||||
```
|
||||
|
||||
The `getClusterConfigFromCloudlyByIdentity` method retrieved the configuration needed to set up and manage your clusters within the multi-cloud environment.
|
||||
## 📚 Core Operations
|
||||
|
||||
### Advanced Communication via Typed Sockets
|
||||
|
||||
The API client leverages `TypedRequest` and `TypedSocket` from the `@api.global` family, enabling statically-typed, real-time communication. Here's an example demonstrating socket integration:
|
||||
### 🐳 Image Management
|
||||
|
||||
```typescript
|
||||
async function configureSocketCommunication(client: CloudlyApiClient) {
|
||||
client.configUpdateSubject.subscribe({
|
||||
next: (configData) => {
|
||||
console.log('Received configuration update:', configData);
|
||||
}
|
||||
});
|
||||
// Create an image entry
|
||||
const image = await client.images.createImage({
|
||||
name: 'my-app',
|
||||
description: 'Production application image'
|
||||
});
|
||||
|
||||
client.serverActionSubject.subscribe({
|
||||
next: (actionRequest) => {
|
||||
console.log('Server action requested:', actionRequest);
|
||||
}
|
||||
});
|
||||
}
|
||||
// Push a new version
|
||||
const imageStream = fs.createReadStream('app.tar');
|
||||
await image.pushImageVersion('2.0.0', imageStream);
|
||||
|
||||
configureSocketCommunication(cloudlyClient);
|
||||
// List all images
|
||||
const images = await client.images.listImages();
|
||||
```
|
||||
|
||||
The client utilizes RxJS `Subject` to enable simple yet powerful handling of incoming socket requests, whereby one can act upon updates and actions as they occur.
|
||||
|
||||
### Integrating Certificates
|
||||
|
||||
Certificate operations, such as obtaining SSL certificates for your domains, are also streamlined using this API client:
|
||||
### 🌐 Cluster Operations
|
||||
|
||||
```typescript
|
||||
async function retrieveCertificate(client: CloudlyApiClient, domainName: string, identity) {
|
||||
const certificate = await client.getCertificateForDomain({
|
||||
domainName: domainName,
|
||||
type: 'ssl',
|
||||
identity: identity
|
||||
});
|
||||
// Get cluster configuration
|
||||
const clusterConfig = await client.getClusterConfigFromCloudlyByIdentity(identity);
|
||||
|
||||
console.log('Retrieved SSL Certificate:', certificate);
|
||||
}
|
||||
|
||||
const yourDomain = 'example.com';
|
||||
await retrieveCertificate(cloudlyClient, yourDomain, identity);
|
||||
// Deploy to cluster
|
||||
await client.deployToCluster({
|
||||
clusterName: 'production',
|
||||
serviceName: 'api-service',
|
||||
image: 'my-app:2.0.0',
|
||||
replicas: 3
|
||||
});
|
||||
```
|
||||
|
||||
This example demonstrates fetching SSL certificates using given domain credentials and an authenticated identity.
|
||||
|
||||
### API Client Cleanup
|
||||
|
||||
When operations are complete and the application is shutting down, it's crucial to gracefully terminate the API client connection:
|
||||
### 🔒 Certificate Management
|
||||
|
||||
```typescript
|
||||
async function cleanup(client: CloudlyApiClient) {
|
||||
await client.stop();
|
||||
console.log('Cloudly API client disconnected gracefully.');
|
||||
}
|
||||
// Request SSL certificate
|
||||
const certificate = await client.getCertificateForDomain({
|
||||
domainName: 'api.example.com',
|
||||
type: 'ssl',
|
||||
identity: identity
|
||||
});
|
||||
|
||||
await cleanup(cloudlyClient);
|
||||
// Use certificate in your application
|
||||
console.log('Certificate:', certificate.cert);
|
||||
console.log('Private Key:', certificate.key);
|
||||
```
|
||||
|
||||
By invoking the `stop` method, the API client securely terminates its connection to ensure no resources are left hanging, preventing potential memory leaks.
|
||||
### 🔐 Secret Management
|
||||
|
||||
### Miscellaneous Features
|
||||
```typescript
|
||||
// Create secret group
|
||||
const secretGroup = await client.secrets.createSecretGroup({
|
||||
name: 'api-secrets',
|
||||
secrets: [
|
||||
{ key: 'DATABASE_URL', value: 'postgres://...' },
|
||||
{ key: 'REDIS_URL', value: 'redis://...' }
|
||||
]
|
||||
});
|
||||
|
||||
This section would be remiss without mentioning various utility functionalities such as secret management, server actions, DNS configurator options, and more, all underpinned by an intelligently designed API, enriching cloud resource interactivity.
|
||||
// Retrieve secrets
|
||||
const secrets = await client.secrets.getSecretGroup('api-secrets');
|
||||
```
|
||||
|
||||
In conclusion, by employing `@serve.zone/api`, developers gain unparalleled access to a multitude of modular functions pertinent to multi-cloud administration, significantly amplifying productivity and management effectiveness across diverse computing environments.
|
||||
## 🔄 Real-Time Updates
|
||||
|
||||
Subscribe to configuration changes and server actions using RxJS:
|
||||
|
||||
```typescript
|
||||
// Listen for configuration updates
|
||||
client.configUpdateSubject.subscribe({
|
||||
next: (config) => {
|
||||
console.log('📡 Configuration updated:', config);
|
||||
// React to configuration changes
|
||||
}
|
||||
});
|
||||
|
||||
// Handle server action requests
|
||||
client.serverActionSubject.subscribe({
|
||||
next: (action) => {
|
||||
console.log('⚡ Server action:', action.type);
|
||||
// Process server-initiated actions
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## 🎯 Advanced Usage
|
||||
|
||||
### Streaming Operations
|
||||
|
||||
```typescript
|
||||
// Stream logs from a service
|
||||
const logStream = await client.logs.streamLogs({
|
||||
service: 'api-service',
|
||||
follow: true
|
||||
});
|
||||
|
||||
logStream.on('data', (log) => {
|
||||
console.log(log.message);
|
||||
});
|
||||
```
|
||||
|
||||
### Batch Operations
|
||||
|
||||
```typescript
|
||||
// Deploy multiple services
|
||||
const deployments = await Promise.all([
|
||||
client.deploy({ service: 'frontend', image: 'app:latest' }),
|
||||
client.deploy({ service: 'backend', image: 'api:latest' }),
|
||||
client.deploy({ service: 'worker', image: 'worker:latest' })
|
||||
]);
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
```typescript
|
||||
try {
|
||||
await client.start();
|
||||
} catch (error) {
|
||||
if (error.code === 'AUTH_FAILED') {
|
||||
console.error('Authentication failed:', error.message);
|
||||
} else if (error.code === 'CONNECTION_LOST') {
|
||||
console.error('Connection lost, retrying...');
|
||||
await client.reconnect();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 🧹 Cleanup
|
||||
|
||||
Always gracefully disconnect when done:
|
||||
|
||||
```typescript
|
||||
// Stop the client connection
|
||||
await client.stop();
|
||||
console.log('✅ Disconnected cleanly');
|
||||
```
|
||||
|
||||
## 🔌 API Reference
|
||||
|
||||
### CloudlyApiClient
|
||||
|
||||
Main client class for interacting with Cloudly.
|
||||
|
||||
#### Constructor Options
|
||||
|
||||
```typescript
|
||||
interface ICloudlyApiClientOptions {
|
||||
registerAs: TClientType; // 'api' | 'cli' | 'web'
|
||||
cloudlyUrl: string; // Full URL including protocol and port
|
||||
}
|
||||
```
|
||||
|
||||
#### Methods
|
||||
|
||||
- `start()` - Initialize connection
|
||||
- `stop()` - Close connection
|
||||
- `getIdentityByToken()` - Authenticate with token
|
||||
- `getClusterConfigFromCloudlyByIdentity()` - Get cluster configuration
|
||||
- `getCertificateForDomain()` - Request SSL certificate
|
||||
- `images` - Image management namespace
|
||||
- `secrets` - Secret management namespace
|
||||
- `clusters` - Cluster management namespace
|
||||
|
||||
## 🎬 Complete Example
|
||||
|
||||
```typescript
|
||||
import { CloudlyApiClient } from '@serve.zone/api';
|
||||
|
||||
async function main() {
|
||||
// Initialize client
|
||||
const client = new CloudlyApiClient({
|
||||
registerAs: 'api',
|
||||
cloudlyUrl: 'https://cloudly.example.com:443'
|
||||
});
|
||||
|
||||
try {
|
||||
// Connect and authenticate
|
||||
await client.start();
|
||||
const identity = await client.getIdentityByToken(process.env.SERVICE_TOKEN, {
|
||||
tagConnection: true,
|
||||
statefullIdentity: true
|
||||
});
|
||||
|
||||
// Create and deploy an image
|
||||
const image = await client.images.createImage({
|
||||
name: 'my-service',
|
||||
description: 'Microservice application'
|
||||
});
|
||||
|
||||
// Push image version
|
||||
const stream = getImageStream(); // Your image stream
|
||||
await image.pushImageVersion('1.0.0', stream);
|
||||
|
||||
// Deploy to cluster
|
||||
await client.deployToCluster({
|
||||
clusterName: 'production',
|
||||
serviceName: 'my-service',
|
||||
image: 'my-service:1.0.0',
|
||||
replicas: 3,
|
||||
environment: {
|
||||
NODE_ENV: 'production'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('✅ Deployment successful!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error:', error);
|
||||
} finally {
|
||||
await client.stop();
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
@@ -199,4 +303,4 @@ 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.
|
||||
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