api.ts


Overview

The [api.ts](/projects/291/69281) file is a core utility module responsible for deploying API services for blockchain coinstacks onto Kubernetes clusters using Pulumi. It automates the creation and management of the Kubernetes Deployment, Service, ServiceMonitor, TLS certificates, and ingress routing for the API layer of a blockchain application stack. The module handles container image building and pushing (including caching and tagging), configures resource limits, readiness and liveness probes, and optionally sets up horizontal pod autoscaling.

This file abstracts the complexities involved in deploying stateless API services for multiple blockchain coinstacks implemented in either Go or Node.js, ensuring consistent, scalable, and secure deployments.


Exports

Interfaces

Autoscaling

Represents configuration options for horizontal pod autoscaling of the API deployment.

Property

Type

Description

`enabled`

boolean

Indicates if autoscaling is enabled.

`maxReplicas`

number

Maximum number of replica pods allowed.

`cpuThreshold`

number

CPU usage percentage threshold to trigger scaling actions.

ApiConfig

Defines resource and scaling configurations for the API deployment.

Property

Type

Description

`cpuLimit`

string

CPU limit for the container (e.g., "500m").

`cpuRequest?`

string

(Optional) CPU resource request for scheduling.

`memoryLimit`

string

Memory limit for the container (e.g., "512Mi").

`replicas`

number

Number of API replicas to deploy.

`autoscaling?`

`Autoscaling`

(Optional) Autoscaling configuration.

DeployApiArgs

Arguments required to deploy an API service.

Property

Type

Description

`appName`

string

Application name identifier.

`assetName`

string

Asset name (used in resource naming and labels).

`coinstack`

string

The blockchain coinstack identifier (e.g., "thorchain", "bitcoin").

`coinstackType`

`CoinstackType`

The type of coinstack implementation ("go" or "node").

baseImageName?

string

(Optional) Base Docker image to use or cache from.

`sampleEnv`

Buffer

Environment variables sample file content for secrets injection.

`config`

Pick

'dockerhub'

`deployDependencies?`

Input>

(Optional) Pulumi dependencies to order deployment.

`namespace`

string

Kubernetes namespace to deploy resources into.

`provider`

`k8s.Provider`

Pulumi Kubernetes provider instance.

`port?`

number

(Optional) API service port; defaults to 3000.


Functions

deployApi(args: DeployApiArgs): Promise<k8s.apps.v1.Deployment | undefined>

Deploys the API service for a blockchain coinstack as a Kubernetes Deployment with associated networking, monitoring, ingress, and autoscaling.

Parameters

Returns

Description

The function performs the following key steps:

  1. Configuration Validation: If API config (config.api) is undefined, the function returns early without deploying anything.

  2. Docker Image Handling:

    • Computes a unique image tag based on the coinstack source and build arguments via getCoinstackHash.

    • Constructs the image name using either a public default repository (shapeshiftdao/...) or a configured Docker Hub repository.

    • Checks if the image tag exists remotely; if not, builds and pushes the Docker image using buildAndPushImage.

    • Supports different Docker build contexts and Dockerfile paths depending on the coinstack type (Go or Node).

  3. Kubernetes Service Creation:

    • Creates a ClusterIP Service exposing the API pod on the configured port.

  4. Prometheus ServiceMonitor Creation:

    • Creates a ServiceMonitor custom resource for Prometheus to scrape metrics from the API service.

  5. TLS Certificate and Ingress Setup (if root domain is configured):

    • Creates a Certificate resource managed by cert-manager for HTTPS termination.

    • Creates Traefik IngressRoute custom resource with routing rules matching the domain.

    • Creates a basic Ingress resource as fallback or compatibility.

  6. Pod Template and Deployment Configuration:

    • Defines container spec with:

      • Environment variables sourced from secrets (secretEnvs).

      • Resource limits and (optional) requests.

      • Readiness and liveness probes hitting /health.

      • Command or args depending on coinstack type.

    • Creates a Kubernetes Deployment with the specified replica count.

  7. Horizontal Pod Autoscaling (optional):

    • If autoscaling is enabled, creates a HorizontalPodAutoscaler resource targeting the Deployment, scaling between min and max replicas based on CPU utilization.

Usage Example

import * as k8s from '@pulumi/kubernetes'
import { deployApi, DeployApiArgs } from './api'

const args: DeployApiArgs = {
  appName: 'myapp',
  assetName: 'bitcoin',
  coinstack: 'bitcoin',
  coinstackType: 'node',
  sampleEnv: Buffer.from('API_KEY=secret\n'),
  config: {
    api: {
      cpuLimit: '500m',
      memoryLimit: '512Mi',
      replicas: 2,
      autoscaling: {
        enabled: true,
        maxReplicas: 5,
        cpuThreshold: 70,
      },
    },
    dockerhub: {
      username: 'mydockeruser',
      password: 'mypassword',
      server: 'docker.io',
    },
    rootDomainName: 'example.com',
    environment: 'prod',
  },
  namespace: 'default',
  provider: kubeProvider,
}

const deployment = await deployApi(args)

Internal Helper Functions (Not Exported)

getbuildAndPushImageArgs(coinstackType: CoinstackType): Object

Returns Docker build context and Dockerfile path arguments specific to the coinstack type.

getContainer(coinstackType: CoinstackType, coinstack: string): Object

Returns container runtime configuration based on coinstack type.


Implementation Details and Algorithms


Interaction with Other Parts of the System


Class and Function Diagram

classDiagram
    class deployApi {
        +async deployApi(args: DeployApiArgs): Promise<k8s.apps.v1.Deployment | undefined>
    }
    class getbuildAndPushImageArgs {
        +getbuildAndPushImageArgs(coinstackType: CoinstackType): Object
    }
    class getContainer {
        +getContainer(coinstackType: CoinstackType, coinstack: string): Object
    }

    deployApi --> getbuildAndPushImageArgs : uses
    deployApi --> getContainer : uses

Summary

The [api.ts](/projects/291/69281) file encapsulates deployment logic for blockchain API services on Kubernetes, providing a robust, automated, and configurable solution to build container images, deploy Kubernetes resources, configure networking, enable monitoring, and manage autoscaling. Its modular design and integration with Pulumi enable seamless integration into the broader deployment automation framework, facilitating scalable and secure API deployments across diverse blockchain coinstacks.


End of Documentation for api.ts