Keel by ChimpLabs
Jump to page or section Esc
Primitives

Topology

Declarative multi-unit microservice topologies with static boundary enforcement, per-unit PostgreSQL schema isolation, polyglot Rust and Go codegen, and Docker or Cloudflare deployment.

Topology declares a multi-service monorepo in one file. A topology defines shared contracts (Topic and shared resources), per-unit isolation rules, and deployable units.

Starting as a modular monolith? Use Modulith (k.modulith / Modulith) to compose your services in a single unit with a shared database by default, then call App.extract(...) to graduate into a multi-unit Topology with zero service rewrites.

From that declaration, Keel performs four tasks:

  1. Enforces bounded-context ownership at plan time. If two units claim the same Table, Collection, Bucket, Queue, or Cron, Keel fails with TopologyBoundaryError.
  2. Infers cross-unit RPC edges from Service.dependencies without exposing target tables or secrets to calling units.
  3. Runs the full topology in one local Node process through buildTopologyLocalLayer for development and testing.
  4. Deploys the same topology to Docker on a VPS with keelDockerStack / provisionKeelDockerTopology, or to Cloudflare Workers with keelCloudflareStack / provisionKeelCloudflareTopology.

Declaring a topology

Keep pure contracts (Service, IAM, Topic, and Topology) in a shared workspace package, for example @app/contracts, and keep handlers and migrations inside each service package:

import {
  IAM,
  Service,
  Table,
  Topology,
} from "@chimp-labs/keel"

export const App = Topology("acme", {
  // Explicitly shared across units (no ownership conflict)
  shared: {
    iam: AppIam,
    topics: [OrderCreatedTopic],
  },

  // Per-unit isolation defaults
  isolation: {
    database: "schema",      // "schema" | "database" | "instance" | "shared"
    buckets: "unit-scoped",  // "unit-scoped" | "shared"
    workloadAuth: "auto",    // "auto" | "required" | "off"
  },

  // Each key becomes 1 isolated Docker unit or Cloudflare Worker
  units: {
    pdf: {
      services: [PdfRendererService],       // Polyglot Rust or Go service (via `keel codegen`)
      port: 8088,
    },
    orders: {
      services: [OrdersService],            // dependencies: [PdfRendererService], resources: [OrdersTable]
      entrypoint: "apps/orders/src/index.ts",
      migrationsDir: "packages/orders/migrations",
      public: { domain: "api.acme.com" },   // Auto-exposed via edge Caddyfile
    },
  },
})

Static boundary enforcement

Topology(...) validates that one unit owns each stateful resource:

  • Each Table, Collection, Bucket, Queue, Cron, and Service belongs to one unit. Claiming the same resource in two units throws TopologyBoundaryError.
  • Units can share resources listed under shared (iam, topics, tenant, and resources) and remote Service interfaces referenced through dependencies.

Local in-process development (buildTopologyLocalLayer)

Run and test the multi-unit topology in one Node process without containers:

import { Effect } from "effect"
import { KeelMemoryLive, buildTopologyLocalLayer } from "@chimp-labs/keel"

const localLayer = buildTopologyLocalLayer(App, {
  baseLayer: KeelMemoryLive,
  unitLayers: {
    pdf: PdfRendererMockLayer,
    orders: OrdersServiceLive,
  },
})

await Effect.runPromise(program.pipe(Effect.provide(localLayer)))

Service resolution (resolveServiceLayer)

In any TypeScript unit, resolveServiceLayer selects local in-process layers, Docker HTTP RPC, or Cloudflare Workers Service Bindings without changing caller code:

import { resolveServiceLayer } from "@chimp-labs/keel-alchemy/cloudflare"

const PdfClientLayer = resolveServiceLayer(PdfRendererService, {
  local: PdfRendererMockLayer,
  binding: env?.SERVICE_PDF_RENDERER,             // Cloudflare Worker Service Binding
  url: process.env.KEEL_SERVICE_PDF_RENDERER_URL, // Docker / VPS ("http://pdf:8088")
  resilience: {
    timeout: "5 seconds",
    retries: 2,
    workload: {
      service: "orders",
      secret: process.env.KEEL_WORKLOAD_SECRET!,
      forwardUser: true,
    },
  },
})

Polyglot contract codegen (Rust and Go)

You do not need a keel-sdk crate or Go module to implement a polyglot container unit. keel codegen reads the Effect v4 Schema ASTs on your TypeScript Service contract and writes one self-contained contract file. The generated file contains compile-time checked types, closed _tag error unions, X-Keel-Workload-Token HMAC-SHA256 verification, and RPC dispatching.

Rust (keel codegen --lang rust)

Generate a self-contained keel_contract.rs from your TypeScript Service contract. The generated Rust file requires only serde and serde_json in Cargo.toml:

# Generate Rust structs, closed #[serde(tag = "_tag")] error enums, trait,
# embedded SHA-256/HMAC-SHA256 workload verifier, and framework-agnostic dispatch()
pnpm exec keel codegen --lang rust \
  --entry packages/contracts/dist/index.js \
  --service pdf-renderer \
  --out services/rust-pdf/src/keel_contract.rs

# Enforce zero contract drift in CI
pnpm exec keel codegen --lang rust \
  --entry packages/contracts/dist/index.js \
  --service pdf-renderer \
  --out services/rust-pdf/src/keel_contract.rs \
  --check

Implement the generated trait in Rust:

mod keel_contract;
use keel_contract::{
    dispatch, KeelContext, PdfRendererService, RenderPdfError, RenderPdfInput, RenderPdfOutput,
};

struct MyPdfRenderer;

// Compile-time enforced by rustc — fails `cargo check` on any contract drift!
impl PdfRendererService for MyPdfRenderer {
    async fn render_pdf(
        &self,
        ctx: KeelContext,
        input: RenderPdfInput,
    ) -> Result<RenderPdfOutput, RenderPdfError> {
        if input.lines.is_empty() {
            return Err(RenderPdfError::EmptyDocumentError {
                reason: "Document must contain at least one line".into(),
            });
        }
        Ok(RenderPdfOutput {
            pdf_base64: render_pdf(&input),
            page_count: 1.0,
        })
    }
}

Call dispatch(&svc, &body, workload_token, workload_secret.as_deref()).await from Axum, Actix, Hyper, or std::net::TcpListener at POST /_keel/rpc/pdf-renderer (keel_contract::RPC_PATH). Pass --sync to generate synchronous trait methods and dispatch(...).

Go (keel codegen --lang go)

Generate a self-contained keel_contract.go with zero external go.mod dependencies. It uses only the Go standard library packages crypto/hmac, crypto/sha256, crypto/subtle, encoding/base64, encoding/json, and net/http:

# Generate Go structs, literal enums with UnmarshalJSON, sealed _tag error interfaces,
# service interface, stdlib HMAC-SHA256 VerifyWorkloadToken, Dispatch(), and net/http NewHandler()
pnpm exec keel codegen --lang go \
  --entry packages/contracts/dist/index.js \
  --service pdf-renderer \
  --package pdfcontract \
  --out services/go-pdf/pdfcontract/keel_contract.go

# Enforce zero contract drift in CI (--lang golang is also accepted)
pnpm exec keel codegen --lang go \
  --entry packages/contracts/dist/index.js \
  --service pdf-renderer \
  --package pdfcontract \
  --out services/go-pdf/pdfcontract/keel_contract.go \
  --check

Implement the generated Go interface and mount NewHandler on http.ServeMux, Chi, Gin, or Echo:

package main

import (
	"context"
	"log"
	"net/http"
	"os"

	"acme/go-pdf/pdfcontract"
)

type myPdfRenderer struct{}

// Compile-time enforced by `go build` — fails immediately on any contract drift!
func (m *myPdfRenderer) RenderPdf(
	ctx context.Context,
	kctx pdfcontract.KeelContext,
	input pdfcontract.RenderPdfInput,
) (pdfcontract.RenderPdfOutput, pdfcontract.RenderPdfError) {
	if len(input.Lines) == 0 {
		return pdfcontract.RenderPdfOutput{}, pdfcontract.RenderPdfEmptyDocumentError{
			Reason: "Document must contain at least one line",
		}
	}
	return pdfcontract.RenderPdfOutput{
		PdfBase64: renderPdf(input),
		PageCount: 1,
	}, nil
}

func main() {
	mux := http.NewServeMux()
	mux.Handle(
		pdfcontract.RPCPath, // "/_keel/rpc/pdf-renderer"
		pdfcontract.NewHandler(&myPdfRenderer{}, os.Getenv("KEEL_WORKLOAD_SECRET")),
	)
	log.Fatal(http.ListenAndServe(":8088", mux))
}

If you use a framework that does not use net/http, for example Fiber or a custom transport, pass --no-http and call pdfcontract.Dispatch(ctx, svc, rawBody, workloadToken, workloadSecret).

CLI flags and programmatic API

Flag Applies to Description
--lang <rust|go> Both Target language (rust, go, or alias golang).
--entry <path> Both Compiled JS or MJS module exporting a Service or Topology.
--service <name> Both Select one Service when the entry module exports multiple services.
--export <name> Both Select one named export from the entry module.
--out <path> Both Destination file path for the generated contract.
--package <name> Go Go package name. Defaults to the sanitized parent directory name, or keelcontract if that is invalid.
--no-http Go Omit the net/http.Handler adapter (NewHandler) and the net/http and io imports.
--sync Rust Emit synchronous trait methods and dispatch(...) instead of async fn.
--no-auth Both Omit embedded X-Keel-Workload-Token HMAC verification.
--check Both Verify --out matches generated output without writing, exiting with status 1 on drift in CI.

You can also call generateRustServiceContract(service, options) from @chimp-labs/keel-rust and generateGoServiceContract(service, options) from @chimp-labs/keel-go.


Deploying to Docker or Cloudflare

See Alchemy IaC, Docker & Cloudflare for deployment details. keelDockerStack / provisionKeelDockerTopology(App, ...) configures PostgreSQL schema isolation, Garage S3, least-privilege unit env maps, and an edge Caddyfile. keelCloudflareStack / provisionKeelCloudflareTopology(App, ...) deploys Cloudflare Workers with least-privilege R2, KV, Queue, and Service Bindings.