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"). |
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
args: DeployApiArgs— Deployment configuration and contextual information.
Returns
Promise<k8s.apps.v1.Deployment | undefined>— Resolves to the Kubernetes Deployment resource created for the API, orundefinedif API config is missing.
Description
The function performs the following key steps:
Configuration Validation: If API config (
config.api) is undefined, the function returns early without deploying anything.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).
Kubernetes Service Creation:
Creates a
ClusterIPService exposing the API pod on the configured port.
Prometheus ServiceMonitor Creation:
Creates a
ServiceMonitorcustom resource for Prometheus to scrape metrics from the API service.
TLS Certificate and Ingress Setup (if root domain is configured):
Creates a
Certificateresource managed by cert-manager for HTTPS termination.Creates Traefik
IngressRoutecustom resource with routing rules matching the domain.Creates a basic
Ingressresource as fallback or compatibility.
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
Deploymentwith the specified replica count.
Horizontal Pod Autoscaling (optional):
If autoscaling is enabled, creates a
HorizontalPodAutoscalerresource 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.
For
'go': Uses context'../../../'and Dockerfile path'../../../build/Dockerfile'.For
'node': Uses context'../api'and default Dockerfile.Throws error on unknown coinstack type.
getContainer(coinstackType: CoinstackType, coinstack: string): Object
Returns container runtime configuration based on coinstack type.
For
'go': Passes arguments['-swagger', 'swagger.json']to the container.For
'node': Executes the Node.js API app using command['node', 'dist/<coinstack>/api/src/app.js'].Throws error on unknown coinstack type.
Implementation Details and Algorithms
Image Tagging and Caching: The image tag is generated by hashing the coinstack source and build arguments via
getCoinstackHash. This ensures that image tags are content-addressed, facilitating cache efficiency and immutability of deployments.Conditional Docker Build and Push: The system checks if the image with the computed tag exists on the configured Docker registry (
hasTag). If not, it builds and pushes the image usingbuildAndPushImagewith appropriate build arguments and cache sources.Kubernetes Resource Naming and Labeling: All Kubernetes resources (Deployment, Service, ServiceMonitor, Certificate, IngressRoute, Ingress) are named based on the asset name and tier (
api), and consistently labeled withapp,coinstack,asset, andtierlabels for easy selection and monitoring.Ingress Domain Construction: The domain for ingress and TLS certificates is dynamically constructed from the environment, asset name, and root domain, supporting multiple environments (e.g., staging, prod) and additional root domains.
Probes Configuration: Readiness and liveness probes are HTTP GET requests to
/healthendpoint on the API port, with adjusted initial delay for specific coinstacks (e.g., Thorchain requires longer startup).Autoscaling: Horizontal pod autoscaler uses CPU utilization thresholds and scales between configured min replicas and max replicas.
Interaction with Other Parts of the System
Docker Image Build System: Interacts with
buildAndPushImage,hasTag, andgetCoinstackHashutilities from the localindexandhashmodules to manage Docker images.Kubernetes Provider: Uses Pulumi Kubernetes provider to create and manage Kubernetes resources declaratively.
Secret Environment Injection: Imports and uses
secretEnvsfrom thehashmodule to inject secrets and environment variables into the API container.Ingress and TLS Integration: Works alongside Traefik ingress controllers and cert-manager to enable secure and routable API access.
API Configuration: Depends on the global project configuration (
Config) to determine resource limits, Docker registry credentials, domain names, environment settings, and autoscaling options.Deployment Automation Workflow: This file typically gets called from higher-level deployment orchestration functions (e.g.,
deployCoinstack) that manage the overall blockchain stack deployments.
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.