cloudly/ts_interfaces
2024-12-30 00:01:26 +01:00
..
data fix(interfaces): Fix image location schema in IImage interface 2024-12-28 21:48:57 +01:00
platformservice fix(ci): Fix Docker images and npm registry URL in CI workflows 2024-10-27 19:50:39 +01:00
requests feat(external-registry): Introduce external registry management 2024-12-30 00:01:26 +01:00
00_commitinfo_data.ts fix(ci): Fix Docker images and npm registry URL in CI workflows 2024-10-27 19:50:39 +01:00
index.ts fix(ci): Fix Docker images and npm registry URL in CI workflows 2024-10-27 19:50:39 +01:00
plugins.ts fix(ci): Fix Docker images and npm registry URL in CI workflows 2024-10-27 19:50:39 +01:00
readme.md fix(core): Corrected description and devDependencies 2024-10-28 21:49:43 +01:00
tspublish.json feat(dependencies): Upgrade dependencies and include publish orders 2024-11-05 02:06:44 +01:00

@serve.zone/interfaces

interfaces for working with containers

Install

To install @serve.zone/interfaces, run the following command in your terminal:

npm install @serve.zone/interfaces --save

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.

Usage

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.

import { IRequest_GetAllImages } from '@serve.zone/interfaces/requests/image';

class ImageService {
  private cloudlyClient;

  constructor(cloudlyClient: CloudlyApiClient) {
    this.cloudlyClient = cloudlyClient;
  }

  public async fetchAllImages() {
    const request: IRequest_GetAllImages['request'] = {
      identity: this.cloudlyClient.identity,
    };
    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.

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.

import { ILogger, ILogConfig } from '@push.rocks/smartlog-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.

import { IService } from '@serve.zone/interfaces/data/service';

function defineService(): IService {
  return {
    id: 'unique-service-id',
    data: {
      name: 'my-container-service',
      imageId: 'unique-image-id',
      imageVersion: '1.0.0',
      environment: { KEY: 'VALUE' },
      secretBundleId: 'bundle-id',
      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.

4. Network Configuration and Routing

Networking is integral to cloud-native applications. Interfaces in @serve.zone/interfaces help shape network interaction patterns.

import { IReverseProxyConfig } from '@serve.zone/interfaces/data/traffic';

const proxyConfig: IReverseProxyConfig = {
  domain: 'example.com',
  path: '/',
  serviceAddress: 'http://service:8080',
  ssl: true,
};

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.

Advanced Interface Utilization

Monitoring and Metrics Collection

For observability, you can track system metrics using IServerMetrics or cluster status interfaces.

import { IServerMetrics } from '@serve.zone/interfaces/data/server';

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: [],
};

reportMetrics(sampleMetrics);

Implementing such metrics tracking provides insight into performance bottlenecks and helps strategize scaling decisions.

Certificate Management

To handle SSL certificates programmatically, utilize interfaces such as IRequest_Any_Cloudly_GetCertificateForDomain.

import { IRequest_Any_Cloudly_GetCertificateForDomain } from '@serve.zone/interfaces/requests/certificate';

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);
}

Managing certificates dynamically via typed requests simplifies deployment and automates the security dimensions of your applications.

Integrating with External Messaging Services

Use IRequest_SendEmail to integrate platform services for sending emails:

import { IRequest_SendEmail } from '@serve.zone/interfaces/platformservice/mta';

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>',
  };

  await emailClient.sendEmail(emailRequest);
}

This approach demonstrates abstracting the email sending functionality using typed interfaces, contributing to code consistency and robustness.

Conclusion

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.

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.

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 file within this repository.

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.

Company Information

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.

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.