Fluent - Time Saving (TS) utils
Explore the docs Β»
Β·
Report Bug
Β·
Request Feature
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.
# 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- @goatlab/fluent - TypeScript query builder and ORM wrapper with multi-database support via TypeORM
- @goatlab/fluentjs - JavaScript implementation of the Fluent query interface
- @goatlab/fluent-firebase - Firebase/Firestore connector with real-time capabilities
- @goatlab/fluent-loki - LokiJS in-memory database connector
- @goatlab/fluent-pouchdb - PouchDB connector for offline-first applications
- @goatlab/fluent-formio - Form.io API connector for form-based data
- @goatlab/js-utils - Comprehensive utilities for browser and Node.js (arrays, objects, HTTP, promises)
- @goatlab/node-utils - Node.js specific utilities (JWT, encryption, streams, file operations)
- @goatlab/js-html - HTML processing with sanitization and text extraction
- @goatlab/node-xlsx - Excel file streaming and processing
- @goatlab/formio-utils - Form.io form parsing and validation utilities
- @goatlab/queue-core - Unified interface for message brokers (Kafka, RabbitMQ) and job schedulers (Bull, Agenda)
- @goatlab/queue-node - Node.js cron-based scheduler implementation
- @goatlab/tasks-core - Common interface for queueable tasks
- @goatlab/tasks-adapter-gcp - Google Cloud Tasks adapter
- @goatlab/tasks-adapter-hatchet - Hatchet workflow engine adapter
- @goatlab/uploads - Multi-cloud file upload middleware (S3, Google Cloud, Azure)
- @goatlab/node-backend - Flexible caching with Redis and LRU support
- @goatlab/node-metascraper - Web metadata extraction
- @goatlab/metabase - Comprehensive Metabase API wrapper
- @goatlab/typesense - Modern TypeScript wrapper for Typesense search engine
- @goatlab/benchmarks - Performance benchmarking for database operations
- @goatlab/eslint - Shared ESLint configuration
- @goatlab/tsconfig - Shared TypeScript configuration
- @goatlab/ts-package-template - Template for new TypeScript packages
- @sodium/delphi - Multi-agent consensus system with flexible AI model configuration, session management, and production-ready agreement protocols
- PostgreSQL
- MySQL / MariaDB
- SQLite
- Microsoft SQL Server
- Oracle
- MongoDB
- CockroachDB
- SAP Hana
- sql.js
- Firebase / Firestore
- LokiJS (in-memory)
- PouchDB (offline-first)
- Form.io (API-based)
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
# Install dependencies
pnpm install
# Build all packages
pnpm build
# Run tests
pnpm test
# Run development mode
pnpm dev
# Lint code
pnpm lintimport { 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()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.
# 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-orphansThe compose stack uses:
Dockerfileβ multi-stage build (alpine runtime, ~500 MB)docker-compose.ymlβ PG (withfsync=offfor benchmarking β never in prod) + Redis + app- App image runs
packages/delphi-ui/test-server/server.tsvia 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.
# 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.tsWhen 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.
| 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 |
| 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.
We use k6 (brew install k6). Two scripts ship in-tree:
# Requires the test server running on :4445
API_URL=http://localhost:4445 \
k6 run packages/delphi-core/loadtest/k6-workflow.jsHits 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).
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# 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 0All 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.
| 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 |
| 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) |
| 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.
- 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
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 + 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| 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 |
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>&1A 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.
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:
- Disable scheduler in regular workers (env:
DISABLE_SCHEDULER=true) - Run a dedicated single-instance container with
RUN_SCHEDULER_ONLY=true - 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.
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).
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.servefetch handler. Wins on HTTP latency (p50 6ms vs 23ms), loses on engine drain (Bun's Node compat onpg/bullmq).
Both have working examples with one-command load tests:
packages/delphi-express/exampleβ Express + Prisma + Postgres + Redispackages/delphi-bun/exampleβ same stack, swapping Bun for Node
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.
Two ways to keep engine tables organized in your existing schema:
- Postgres schema isolation β pass
schema: 'agents'toWorkflowEngineand engine tables becomeagents.workflow_runsinstead ofpublic.workflow_runs. Pair with PrismapreviewFeatures = ["multiSchema"]and@@schema("agents")directives. - Prisma
@@mapfor client-side renaming β your Prisma client seesprisma.MyAgentRunwhile the physical table staysworkflow_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.
- Architecture, queue-first ingestion, key exports β
packages/delphi-core/README.md - Dashboard + test server + endpoint reference β
packages/delphi-ui/README.md - BullMQ adapter (single vs bulk enqueue, why
addBulkmatters) βpackages/tasks-adapter-bullmq/README.md - Express adapter (router factory, multi-tenant pattern) β
packages/delphi-express/README.md - Bun adapter (fetch handler, reusePort cluster) β
packages/delphi-bun/README.md - Prisma schema fragment for engine tables β
packages/delphi-core/prisma.fragment - LLM adapter, multi-agent consensus β
packages/delphi-ai/README.md - LangGraph integration β
packages/delphi-langgraph/README.md - Sandboxed step execution β
packages/delphi-sandbox/README.md
This monorepo uses Changesets for versioning and publishing.
# Create a changeset
pnpm changeset
# Version packages
pnpm changeset version
# Build and publish
pnpm changeset publishRelease dependency chain: js-utils β node-utils β fluent β other packages
Distributed under the MIT License. See LICENSE for more information.
Ignacio Cabrera - @twitter_handle - ignacio.cabrera@goatlab.io
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 β!