Skip to content
goat-ioPublic

About

Readable query Interface & API generator for JS and Node

Resources

Stars

7 stars

Watchers

1 watching

Forks

Repository files navigation

Stargazers Issues MIT License Commitizen friendly


Logo

GOAT-FLUENT

Fluent - Time Saving (TS) utils
Explore the docs Β»

Β· Report Bug Β· Request Feature

Goat - Fluent (Monorepo)

A comprehensive TypeScript ecosystem for building data-driven applications with unified query interfaces, multi-database support, and extensive utilities for Node.js and browser environments.

πŸš€ Quick Start

# Install the core package
pnpm add @goatlab/fluent

# Install specific database connectors
pnpm add @goatlab/fluent-firebase  # For Firebase/Firestore
pnpm add @goatlab/fluent-loki      # For in-memory database
pnpm add @goatlab/fluent-pouchdb   # For PouchDB

# Install utilities
pnpm add @goatlab/js-utils         # Browser/Node utilities
pnpm add @goatlab/node-utils       # Node.js specific utilities

πŸ“¦ Packages

Core Query Interface

  • @goatlab/fluent - TypeScript query builder and ORM wrapper with multi-database support via TypeORM
  • @goatlab/fluentjs - JavaScript implementation of the Fluent query interface

Database Connectors

Utilities

Task Processing & Queues

Cloud Services

API Integrations

Development Tools

πŸ—„οΈ Supported Databases

Via TypeORM Connector (@goatlab/fluent)

  • PostgreSQL
  • MySQL / MariaDB
  • SQLite
  • Microsoft SQL Server
  • Oracle
  • MongoDB
  • CockroachDB
  • SAP Hana
  • sql.js

Native Connectors

  • Firebase / Firestore
  • LokiJS (in-memory)
  • PouchDB (offline-first)
  • Form.io (API-based)

πŸ—οΈ Architecture

This monorepo follows a modular architecture with:

  • Unified Query Interface: All database connectors implement the same Fluent API
  • Type Safety: Full TypeScript support with Zod schema validation
  • Decorator-based Entities: Define your models using decorators
  • Extensible Connectors: Easy to add new database support
  • Monorepo Structure: Managed with pnpm workspaces and Turbo

πŸ› οΈ Development

# Install dependencies
pnpm install

# Build all packages
pnpm build

# Run tests
pnpm test

# Run development mode
pnpm dev

# Lint code
pnpm lint

πŸ“ Example Usage

import { Fluent, TypeOrmConnector } from '@goatlab/fluent'
import { z } from 'zod'

// Define your schema
const UserSchema = z.object({
  id: z.string(),
  name: z.string(),
  email: z.string().email(),
  age: z.number().optional()
})

// Create a repository
class UserRepository extends TypeOrmConnector<User> {
  constructor() {
    super({
      entity: User,
      dataSource: myDataSource
    })
  }
}

// Use the Fluent API
const users = await userRepo
  .where({ age: { $gte: 18 } })
  .orderBy({ name: 'ASC' })
  .limit(10)
  .find()

βš™οΈ Agent Workflow Engine β€” Run, Test, and Load-Benchmark

This monorepo also ships a distributed agent workflow engine β€” see packages/delphi-core/README.md for the full architecture. This section is the handover for running, testing, and load-benchmarking the engine.

One-shot: run the full stack with Docker

# Build + start app + Postgres 18 + Redis 7 (everything, healthchecks, 2 vCPU/2 GB by default)
docker compose up -d

# App is at http://localhost:4445
curl http://localhost:4445/health
# {"ok":true,"ingestWorkers":<N>,"ingestBufferDepth":0}

# Tear everything down (including volumes)
docker compose down -v --remove-orphans

The compose stack uses:

  • Dockerfile β€” multi-stage build (alpine runtime, ~500 MB)
  • docker-compose.yml β€” PG (with fsync=off for benchmarking β€” never in prod) + Redis + app
  • App image runs packages/delphi-ui/test-server/server.ts via tsx

To bump capacity, edit docker-compose.yml β†’ deploy.resources.limits.cpus. The app auto-detects container CPU and forks cores - 1 cluster workers (CLUSTER_MODE=auto). Override with CLUSTER_MODE=N or off.

Local dev (no Docker for the app)

# Brings up its own Postgres + Redis via testcontainers (Docker daemon needed)
cd packages/delphi-ui
PORT=4445 CLUSTER_MODE=2 PG_POOL_SIZE=20 WORKER_CONCURRENCY=50 \
  npx tsx test-server/server.ts

When PG_HOST and REDIS_HOST env vars are set, the test server connects to those external services instead of starting testcontainers β€” same code, no branching.

Workflows registered in the test server

Name Steps Purpose
fast_single 1 step (fast_echo, ~0ms) Throughput benchmarking
fast_chain 3 steps (a→b→c, ~0ms) DAG benchmarking
demo_pipeline 5 steps with realistic delays + a WAITING_HUMAN review step Demo of HITL flows

HTTP endpoints to know

Endpoint Purpose
POST /workflows/start Sync start (writes PG before responding, ~10–40 ms)
POST /workflows/start-async Queue-first start (returns {runId, traceId} in ~2 ms β€” recommended for high throughput)
POST /workflows/start-batch / start-batch-copy Bulk start (single COPY FROM under the hood)
POST /workflows/status Fetch run + steps; falls back to BullMQ lookup for in-flight QUEUED runs
POST /workflows/ingest-event Event ingestion
GET /health 503 if no ingest worker registered; otherwise {ok, ingestWorkers, ingestBufferDepth}

Full list in packages/delphi-ui/README.md.

Running the load tests

We use k6 (brew install k6). Two scripts ship in-tree:

1. Multi-scenario benchmark (Hatchet-style)

# Requires the test server running on :4445
API_URL=http://localhost:4445 \
  k6 run packages/delphi-core/loadtest/k6-workflow.js

Hits the sync start endpoint by default β€” useful for stress-testing the full DB-first path. Targets 2000 req/s, sweeps multiple scenarios in parallel (single starts, batch starts, event ingest, status polling).

2. Flat sweep (used for the per-CPU benchmarks in this README)

The repo ships an ad-hoc k6-flat.js you can drop into /tmp for sweeps:

// /tmp/k6-flat.js
import http from 'k6/http'
import { check } from 'k6'
import { Counter, Rate, Trend } from 'k6/metrics'

const BASE = __ENV.API_URL || 'http://localhost:4445'
const RATE = parseInt(__ENV.RATE || '5000', 10)
const DUR  = __ENV.DUR || '30s'
const MODE = __ENV.MODE || 'async'   // 'async' | 'single' | 'batch'

const lat = new Trend('lat', true)
const ok  = new Counter('ok')
const err = new Rate('err')
const h = { 'Content-Type': 'application/json' }

export const options = {
  scenarios: {
    flat: {
      executor: 'constant-arrival-rate',
      rate: RATE, timeUnit: '1s', duration: DUR,
      preAllocatedVUs: 200, maxVUs: 1500,
      exec: MODE,
    },
  },
}

export function async() {
  const t = Date.now()
  const r = http.post(BASE + '/workflows/start-async',
    JSON.stringify({ workflowName: 'fast_single', input: { t } }), { headers: h })
  lat.add(Date.now() - t)
  const success = check(r, { '200': x => x.status === 200 })
  if (success) ok.add(1); err.add(!success)
}
export function single() {
  const t = Date.now()
  const r = http.post(BASE + '/workflows/start',
    JSON.stringify({ workflowName: 'fast_single', input: { t } }), { headers: h })
  lat.add(Date.now() - t)
  const success = check(r, { '200': x => x.status === 200 })
  if (success) ok.add(1); err.add(!success)
}

Run sweeps:

# 5 k req/s, 30 s, against the queue-first path
MODE=async RATE=5000 DUR=30s k6 run --quiet /tmp/k6-flat.js

# Sustained soak
MODE=async RATE=5000 DUR=10m k6 run --quiet /tmp/k6-flat.js

Verifying durability after a load test

# Find the running PG container
PG=$(docker ps --format '{{.Names}}' | grep postgres | head -1)

# Total persisted runs
docker exec $PG psql -U agents -d agents -c \
  'SELECT count(*) FROM workflow_runs;'

# Completed vs in-flight
docker exec $PG psql -U agents -d agents -c \
  "SELECT status, count(*) FROM workflow_runs GROUP BY status;"

# Check ingest queue still has backlog (drains naturally)
REDIS=$(docker ps --format '{{.Names}}' | grep redis | head -1)
docker exec $REDIS redis-cli LLEN bull:workflow_ingest:wait
docker exec $REDIS redis-cli LLEN bull:workflow_ingest:active
docker exec $REDIS redis-cli ZCARD bull:workflow_ingest:failed   # should be 0

Performance reference (measured)

All numbers from running packages/delphi-express/example against a fresh stack on an M-series Mac with Docker Desktop (PG + Redis + app colocated). Production with managed PG + managed Redis removes the host-CPU bottleneck.

Per-process ceiling (1 Node process, CLUSTER_MODE=off)

Rate p50 p95 p99 Errors Verdict
1,000 req/s 9ms 29ms 80ms 0% clean
2,000 25ms 54ms 79ms 0% safe ceiling
3,000 71ms 7,009ms 8,851ms 4.29% 🚨 cliff
4,000 78ms 134ms 20,053ms 1.96% overload
6,000 82ms 172ms 18,751ms 3.17% throughput degrading

2-vCPU cluster (CLUSTER_MODE=2)

Rate p50 p95 p99 Errors Sustained
2,000 23ms 62ms 161ms 0% 1,984/s βœ“
4,000 48ms 102ms 192ms 0% 3,908/s βœ“
5,000 80ms 171ms 824ms 0% 4,460/s (healthy)

Horizontal (4 instances Γ— 2 processes, shared infra β€” breaking-point sweep)

Target Actual p95 p99 Errors Verdict
2k 1,999 19ms 60ms 0% βœ… trivial
5k 4,864 156ms 463ms 0% βœ… healthy
10k 5,540 1,314ms 4,733ms 0.02% ⚠ first cliff β€” host CPU saturates
15k 5,828 969ms 5,492ms 0.07% ⚠ accept > drain
20k 5,510 546ms 6,079ms 0.09% ⚠ plateau
25k 3,016 3,005ms 7,636ms 0.06% ⚠ degrading
40k 4,309 1,874ms 3,674ms 0.74% ⚠ deep overload

Graceful overload β€” above the cliff, throughput plateaus but correctness holds: 0 FAILED runs across the entire sweep.

Durability check (5k sustained, 60s)

  • 316,929 fired β†’ 316,930 in agents.workflow_runs β†’ 316,930 COMPLETED (1 from smoke)
  • 0 BullMQ failed jobs Β· 0 FAILED runs
  • Step drain: ~730 completions/sec/instance

Scaling rule of thumb

Budget ~2,000 req/s per Node process. Scale via (a) cluster mode within a pod, (b) horizontal pods. 4 pods Γ— 2 workers = ~5k ingestion (host CPU bound in dev; production linearizes with managed PG/Redis).

Setup Healthy ceiling (p95<200ms, 0% err)
1 instance Γ— 1 process ~2,000 req/s
1 instance Γ— 2 processes (2 vCPU) ~5,000 req/s
4 instances Γ— 2 processes (shared infra, Mac host) ~5,000 req/s (CPU bound)

Reproduce: cd packages/delphi-express/example && pnpm loadtest or pnpm loadtest:horizontal.

Engine-package tests

# Engine + state machine + COPY FROM (277 tests, needs Docker for testcontainers)
cd packages/delphi-core && pnpm test

# Skip the long load-test file
cd packages/delphi-core && npx vitest run --exclude="**/load-test*"

# AI layer (63 tests, no containers)
cd packages/delphi-ai && pnpm test

# Sandbox unit + integration tests
cd packages/delphi-sandbox && pnpm test:unit
cd packages/delphi-sandbox && pnpm test:integration

# Visual editor E2E (Playwright, 12 tests)
cd packages/delphi-ui && npx playwright test e2e/workflow-editor.spec.ts

Tuning knobs (env vars)

Env Default Purpose
PORT 4444 / 4445 HTTP port
CLUSTER_MODE auto auto (cores-1), off (single proc), or integer N
PG_POOL_SIZE 20 Postgres pool per Node process. Total connections = workers Γ— this. Cap below max_connections.
WORKER_CONCURRENCY 50 BullMQ concurrency per step queue per process
DISABLE_LOG_BUFFER false true β†’ synchronous log writes (debugging only)
INGEST_TIMING unset 1 β†’ log per-flush COPY wall-time breakdown (begin / runs / steps / commit)
PG_HOST, PG_PORT, PG_DB, PG_USER, PG_PASSWORD β€” If set, app skips testcontainers and connects to external PG
REDIS_HOST, REDIS_PORT β€” Same idea for Redis

Retention (delete old runs)

Tables grow forever without a cleanup job. The repo ships a one-shot script that drops terminal-state runs older than RETENTION_DAYS (active runs preserved regardless of age). Steps and logs are removed via ON DELETE CASCADE.

# One-shot (default 'public' schema)
DATABASE_URL=postgres://agents:agents@localhost:5432/agents \
RETENTION_DAYS=30 \
  npx tsx packages/delphi-core/bin/retention-cleanup.ts

# Engine deployed with schema='agents' β€” MUST set RETENTION_SCHEMA to match
DATABASE_URL=$DATABASE_URL \
RETENTION_SCHEMA=agents \
RETENTION_DAYS=30 \
  npx tsx packages/delphi-core/bin/retention-cleanup.ts

# Crontab β€” hourly
0 * * * * cd /app && DATABASE_URL=$DATABASE_URL RETENTION_SCHEMA=agents RETENTION_DAYS=30 \
  npx tsx packages/delphi-core/bin/retention-cleanup.ts >> /var/log/retention.log 2>&1

A Kubernetes CronJob template is in the script's header comment. For installations >500GB, also enable the autovacuum overrides shown commented in docker-compose.yml β€” without aggressive vacuum, table bloat compounds even with retention enabled.

When the scheduler becomes the bottleneck

SchedulerService (cron triggers + delayed runs) currently runs in-process inside every cluster worker. That's fine for hundreds of triggers/min. If you find scheduler tick latency or trigger-fire warnings dominating the engine logs (per Hatchet's note: "If you observe a large number of warnings, consider isolating the scheduler"), extract it:

  1. Disable scheduler in regular workers (env: DISABLE_SCHEDULER=true)
  2. Run a dedicated single-instance container with RUN_SCHEDULER_ONLY=true
  3. Same Postgres + Redis as the rest β€” coordination is via PG row locks

This is an explicit follow-up; the env-var flags don't exist yet, but the SchedulerService is already a separate class β€” extracting requires only a CLI flag and is a ~1 hour change when needed.

Internal write buffers

The engine uses the WriteBuffer<T> primitive (packages/delphi-core/src/engine/WriteBuffer.ts) to batch writes Hatchet-style. Currently wired up:

Buffer Threshold / Interval Purpose
IngestBuffer (HTTP→Redis) 200 / 50ms accumulate start-async triggers, flush via addBulk
IngestWorker (Redis→PG) 200 / 20ms accumulate BullMQ jobs, flush via COPY FROM
logBuffer (step events→PG) 50 / 50ms batch workflow_step_logs writes via COPY FROM

Planned next: a StepStatusBuffer for markStepRunning / onStepCompleted UPDATEs (1.5–2Γ— completion throughput per Hatchet's pattern). Designed but not yet implemented β€” requires changes to BullMQ ack semantics so the per-job promise only resolves after the batched UPDATE commits. See the design comment in WorkflowEngine.ts (search for DESIGN: Step-status batching).

Plug into your own backend (Express, Bun, Next.js, etc.)

The engine is framework-agnostic. Two adapters ship today:

  • @goatlab/delphi-express β€” Express Router for Node backends. ~250 LOC. ~4.5k req/s sustained @ p95<200ms on 2 vCPU.
  • @goatlab/delphi-bun β€” Bun.serve fetch handler. Wins on HTTP latency (p50 6ms vs 23ms), loses on engine drain (Bun's Node compat on pg/bullmq).

Both have working examples with one-command load tests:

For Express:

import { agentsRouter } from '@goatlab/delphi-express'

app.use('/api/workflows', agentsRouter({
  resolveAgents: async (req) => {
    const { engine, ingestBuffer } = await myFactory(req)   // your code, cached per tenant
    return { engine, ingestBuffer, tenantId: req.user.tenantId }
  },
}))

That's it β€” every workflow endpoint (start-async, status, signal, etc.) is now mounted under /api/workflows. See the delphi-express README for selective routes, custom error mapping, and a complete multi-tenant factory example.

Schema isolation + Prisma integration

Two ways to keep engine tables organized in your existing schema:

  1. Postgres schema isolation β€” pass schema: 'agents' to WorkflowEngine and engine tables become agents.workflow_runs instead of public.workflow_runs. Pair with Prisma previewFeatures = ["multiSchema"] and @@schema("agents") directives.
  2. Prisma @@map for client-side renaming β€” your Prisma client sees prisma.MyAgentRun while the physical table stays workflow_runs. No engine change needed.

Drop-in prisma.fragment ships all 12 engine models with proper indexes β€” copy into your schema.prisma and migrate via your existing tool (Prisma Migrate, pgroll, etc.). The engine does not auto-bootstrap when you provide your own schema β€” migration ownership stays with your tooling.

Where to dig deeper

🚒 Release Process

This monorepo uses Changesets for versioning and publishing.

# Create a changeset
pnpm changeset

# Version packages
pnpm changeset version

# Build and publish
pnpm changeset publish

Release dependency chain: js-utils β†’ node-utils β†’ fluent β†’ other packages

License

Distributed under the MIT License. See LICENSE for more information.

Contact

Ignacio Cabrera - @twitter_handle - ignacio.cabrera@goatlab.io

Acknowledgments

This library is based on the work of other Authors and Open Source Libraries. Have a look at them and give them a well deserved Star ⭐!

About

Readable query Interface & API generator for JS and Node

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages