@latsabben-hq/hubben-client
v3.0.0
Published
Transactional durable usage outbox, heartbeat and manifest reporting for Hubben.
Readme
Hubben client SDK
Purpose
@latsabben-hq/hubben-client 3 records billable usage in the application's Postgres transaction, then delivers it durably to Hubben. Heartbeat and manifest reporting remain best effort.
Install
bun add @latsabben-hq/hubben-client@^3 postgres
# Optional, for Drizzle transactions:
bun add drizzle-orm
DATABASE_URL=postgres://... bunx hubben-client migrateNode 18+; no runtime dependencies. Postgres-js and Drizzle are optional peers. Migration needs postgres-js. Configure the application's Drizzle migration schema filter as schemaFilter: ['public']; the SDK alone owns schema hubben.
Usage
import postgres from 'postgres'
import { migrateOutbox, flushOutbox, startMeter } from '@latsabben-hq/hubben-client'
import { track } from '@latsabben-hq/hubben-client/drizzle'
const sql = postgres(process.env.DATABASE_URL!)
// Run once in the release step, before serving requests:
await migrateOutbox(sql)
await db.transaction(async (tx) => {
await tx.insert(orders).values(order)
await track(tx, 'orders', 1, { id: order.eventId })
})
const meter = startMeter({ sql, url: process.env.HUBBEN_URL, key: process.env.HUBBEN_KEY })
// In jobs, or during graceful termination:
meter.stop()
await flushOutbox({ sql, url: process.env.HUBBEN_URL!, key: process.env.HUBBEN_KEY! })For postgres-js, import track from @latsabben-hq/hubben-client/postgres (or the root) and use sql.begin(async tx => { …; await track(tx, 'orders', 1) }).
API
migrateOutbox(sql, { schema? }): idempotent, advisory-locked, versioned migration. Schema override is for isolated tests only.track(tx, metric, value, { id?, at?, properties? }): returns the event id; writes in the caller's transaction and throws on every failure. Default id is a ULID. Stable id + identical content is idempotent; changed content throws. Omittedatreuses an existing id's timestamp on retries.flushOutbox({ sql, url, key, batchSize = 500, maxBatches = 10, schema? }): returns{ batches, sent, rejected, retried, unauthorized, error? }. Errors are reported without throwing. Inspect the report and retained rejection reasons.startMeter({ sql, url?, key?, intervalMs = 30000 }): returns{ stop() }; missing credentials are a no-op. Background delivery never throws into the host process. Stop prevents future ticks; an active flush may finish.pruneOutbox(sql, { sentDays = 35, rejectedDays = 90, schema? }): removes expired terminal rows, returns deleted count. Schedule daily.createHubben({ url, key, flushIntervalMs? }): unchanged legacy API (track,flush,heartbeat,startHeartbeat,reportManifest,shutdown).reportManifest({ blueprint?, packages, app_version?, git_sha? })lists every library package the app uses; the response reportsunknownPackagesanddrift. Use its heartbeat and manifest methods with rejection handlers. Its legacy usage queue is in memory; use transactionaltrackfor billing.- Types:
TrackOptions,FlushOptions,FlushReport,OutboxRequest,OutboxResponse,OutboxSource,OutboxSql, and the legacy heartbeat/manifest/usage types.
Integration
Keep keys server-side. Use a deployment key, not an operator MCP token. Start one meter per process; replicas share source identity and lease rows with SKIP LOCKED. Flushing commits leases before HTTP and sends empty batches to report completeness. An expired 60-second lease is replayed safely through server deduplication. Delivery failures back off with jitter and honor Retry-After; 401/403 stop the flush, retain pending rows, and leave the lease to expire.
The persisted cutoff lock protects slow transactions. Events cannot precede the cutoff or be backdated more than ten minutes or future-dated more than five minutes. The watermark lags at least fifteen minutes. Unknown metrics are retained as rejected; fix the metric configuration and investigate before billing approval. Never edit the cutoff to bypass completeness.
Customizing
Choose stable business event ids for application retries. Metric values must fit nonnegative numeric(20,6); money is integer cents. Properties must be JSON objects. Adjust batch limits and timer intervals to your workload, keeping batches at most 500. Use flushOutbox in short-lived jobs and scheduled handlers.
Gotchas
Always await track inside the business transaction and allow its exception to roll that transaction back. No network call runs on this path. Do not catch a tracking error and commit the business write. A database outage must fail the billable action so usage cannot be lost. Catch heartbeat/manifest failures separately. Do not share the database/source id across unrelated apps, restore an old database snapshot into an active source, or prune pending rows. Pruning rejected rows reduces the reported retained rejection count; retain them for diagnosis until resolved. Explicit legacy heartbeat/manifest/flush calls can reject; background errors are suppressed.
