Server API
Create HTTP API endpoints for Duron using the server module
Duron provides a server module for creating HTTP API endpoints. This is useful for building dashboards, monitoring tools, or integrating Duron with other services.
Installation
The server module is included with Duron. No additional installation is required.
Creating a Server
Create a server using the createServer() function:
import { createServer } from 'duron/server'
import { duron } from 'duron'
import { pgliteAdapter } from 'duron/adapters/pglite'
// Create your Duron client
const client = duron({
database: pgliteAdapter({ connection: ':memory:' }),
actions: {
sendEmail,
},
})
// Create the server
const app = createServer({
client,
prefix: '/api', // Optional, defaults to '/api'
login: {
onLogin: async ({ email, password }) => {
// Implement your authentication logic
return email === 'admin@example.com' && password === 'password'
},
jwtSecret: process.env.JWT_SECRET || 'your-secret-key',
expirationTime: '1h', // Optional, defaults to '1h'
},
})
// Start your server (using Elysia/Bun)
app.listen(3000)Server Options
client
Required. The Duron client instance to use for API endpoints.
{
client: myDuronClient,
}prefix
Optional. Prefix for all routes. Defaults to '/api'.
{
prefix: '/api/v1',
}login
Optional. Configuration object for authentication. When provided, all API endpoints require authentication via JWT tokens.
{
login: {
onLogin: async ({ email, password }) => {
// Validate credentials
const user = await db.users.findByEmail(email)
if (!user) return false
return await bcrypt.compare(password, user.password)
},
jwtSecret: process.env.JWT_SECRET || 'your-secret-key',
},
}login.onLogin
Required when login is provided. Function to handle login requests.
Parameters:
email- User emailpassword- User password
Returns: Promise resolving to true if login succeeds, false otherwise
login.jwtSecret
Required when login is provided. Secret key for JWT token generation. Can be a string or Uint8Array. Should be a secure random string in production.
{
login: {
jwtSecret: process.env.JWT_SECRET || 'your-secret-key',
// or
jwtSecret: new Uint8Array([...]), // Uint8Array is also supported
},
}login.expirationTime
Optional. Expiration time for the access JWT token. Defaults to '1h'. Accepts any valid time string format (e.g., '1h', '7d', '30m').
{
login: {
jwtSecret: process.env.JWT_SECRET || 'your-secret-key',
expirationTime: '30m', // Access token expires in 30 minutes
},
}login.refreshTokenExpirationTime
Optional. Expiration time for the refresh token. Defaults to '7d'. Accepts any valid time string format.
{
login: {
jwtSecret: process.env.JWT_SECRET || 'your-secret-key',
expirationTime: '1h',
refreshTokenExpirationTime: '30d', // Refresh token expires in 30 days
},
}API Endpoints
All endpoints use Standard Schema for input and response validation.
Authentication
POST /login
Authenticate and receive JWT tokens.
Request Body:
{
"email": "user@example.com",
"password": "password"
}Response:
{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}Status Codes:
200- Success401- Invalid credentials400- Validation error
Jobs
GET /jobs
Get matching jobs from active and archive storage with global sorting and pagination. Job records include input, output, and error, but not steps. Restored terminal jobs remain visible under their status filters.
SQL adapters apply sort keys in the supplied order, followed by job ID for ties in the
direction of the last sort key, so pages are stable while the jobs do not change. The
default sort is startedAt:desc. Nulls sort last ascending and first descending; text
uses byte order (Unicode code point order in a UTF-8 database), independent of the
database locale; dates sort by their stored microsecond precision; and duration sorts
numeric durationMs. Unfiltered sorts by createdAt, startedAt and status use
indexes; filtered listings may scan and sort the matching jobs instead.
total includes all matching jobs even when the page is empty. Count and page are
separate queries, not a method-wide or cross-request snapshot. At most pageSize
job payloads return from the database; payload size, database work, and latency are
not bounded by this limit.
Query Parameters:
page- Page number (default: 1)pageSize- Items per page (default: 10, max: 1000)fStatus- Filter by status (comma-separated or multiple params)fActionName- Filter by action name (comma-separated or multiple params)fGroupKey- Filter by group key (comma-separated or multiple params)fClientId- Filter by client ID (comma-separated or multiple params)fDescription- Filter by job description (fuzzy match)fCreatedAt- Filter by created date (ISO string or JSON array[start, end])fStartedAt- Filter by started date (ISO string or JSON array[start, end])fFinishedAt- Filter by finished date (ISO string or JSON array[start, end])fUpdatedAfter- Filter by updated after date (ISO string)fSearch- Fuzzy search in job datafInputFilter- JSONB filter on input (JSON string)fOutputFilter- JSONB filter on output (JSON string)sort- Sort string format:"field:asc,field:desc"(fields:createdAt,startedAt,finishedAt,status,actionName,expiresAt,duration,description)
Example:
GET /api/jobs?page=1&pageSize=20&fStatus=active,completed&sort=createdAt:descResponse: { jobs, total, page, pageSize }. Timestamps are serialized as ISO
strings (or null for nullable timestamps); durationMs is a number or null.
{
"jobs": [
{
"id": "uuid",
"actionName": "sendEmail",
"groupKey": "user-123",
"description": "Send email to user@example.com",
"status": "completed",
"input": { "to": "user@example.com" },
"output": { "success": true },
"error": null,
"timeoutMs": 60000,
"expiresAt": "2024-01-01T00:01:01.000Z",
"createdAt": "2024-01-01T00:00:00.000Z",
"startedAt": "2024-01-01T00:00:01.000Z",
"finishedAt": "2024-01-01T00:00:05.000Z",
"updatedAt": "2024-01-01T00:00:05.000Z",
"concurrencyLimit": 1,
"concurrencyStepLimit": 1,
"actionConcurrencyLimit": null,
"clientId": "worker-1",
"durationMs": 4000
}
],
"page": 1,
"pageSize": 20,
"total": 100
}GET /jobs/:id
Get a job by its ID (all job fields, as in GET /jobs; 404 when it does not exist).
Response:
{
"id": "uuid",
"actionName": "sendEmail",
"description": "Send email to user@example.com",
"status": "completed",
"input": { "to": "user@example.com" },
"output": { "success": true },
"createdAt": "2024-01-01T00:00:00Z",
"startedAt": "2024-01-01T00:00:01Z",
"finishedAt": "2024-01-01T00:00:05Z",
"updatedAt": "2024-01-01T00:00:05Z"
}GET /jobs/:id/status
Get job status and updatedAt timestamp.
Response:
{
"status": "completed",
"updatedAt": "2024-01-01T00:00:05Z"
}POST /jobs/:id/cancel
Cancel a job with client.cancelJob(). success is true whenever the call does not fail; it does not tell whether the job was still running or waiting.
Response:
{
"success": true,
"message": "Job uuid has been cancelled"
}POST /jobs/:id/retry
Retry a failed job. When the job cannot be retried, the response is 500 with an error message.
Response:
{
"success": true,
"message": "Job uuid has been retried",
"newJobId": "new-uuid"
}POST /jobs/:id/time-travel
Time travel a job to restart from a specific step. The job must be in completed, failed, or cancelled status. Which steps are kept is described in timeTravelJob. When the time travel is not possible, the response is 500 with an error message.
Request Body:
{
"stepId": "step-uuid"
}Response:
{
"success": true,
"message": "Job uuid has been time traveled to step step-uuid"
}DELETE /jobs/:id
Delete a job by its ID. Active jobs cannot be deleted.
Response:
{
"success": true,
"message": "Job uuid has been deleted"
}Status Codes:
200- Success404- Job not found or cannot be deleted (active jobs)
DELETE /jobs
Delete multiple jobs using the same query parameters as GET /jobs. Active jobs are excluded from deletion.
Query Parameters: Same as GET /jobs
Response:
{
"success": true,
"message": "Deleted 5 job(s)",
"deletedCount": 5
}Steps
GET /jobs/:id/steps
Get all matching steps from active and archive storage, ordered by createdAt ascending.
This endpoint has no pagination.
Query Parameters:
search- Optional search in step names or output. SQL adapters use case-insensitive name matching (including SQL%and_wildcards) or English full-text output search.fUpdatedAfter- Optional ISO date string. Only steps whoseupdatedAt, truncated to milliseconds, is strictly greater than this date are returned, for either search branch.
Response: { steps, total }, where total equals the number of returned steps after filtering.
Output is searchable but omitted from this response; use GET /steps/:id to retrieve it.
{
"steps": [
{
"id": "uuid",
"jobId": "job-uuid",
"parentStepId": null,
"parallel": false,
"name": "fetchUser",
"status": "completed",
"error": null,
"timeoutMs": 30000,
"expiresAt": "2024-01-01T00:00:31Z",
"retriesLimit": 3,
"retriesCount": 0,
"delayedMs": null,
"historyFailedAttempts": {},
"createdAt": "2024-01-01T00:00:00Z",
"startedAt": "2024-01-01T00:00:01Z",
"finishedAt": "2024-01-01T00:00:02Z",
"updatedAt": "2024-01-01T00:00:02Z"
}
],
"total": 1
}GET /steps/:id
Get a step by its ID.
Response:
{
"id": "uuid",
"jobId": "job-uuid",
"name": "fetchUser",
"status": "completed",
"output": { "id": "123", "name": "John" },
"createdAt": "2024-01-01T00:00:00Z",
"startedAt": "2024-01-01T00:00:01Z",
"finishedAt": "2024-01-01T00:00:02Z",
"updatedAt": "2024-01-01T00:00:02Z"
}GET /steps/:id/status
Get step status and updatedAt timestamp.
Response:
{
"status": "completed",
"updatedAt": "2024-01-01T00:00:02Z"
}Archive
These endpoints call the Client's archive methods. They require authentication.
GET /archive/stats
Get archive statistics.
Response:
{
"jobsCount": 1200,
"stepsCount": 5400,
"oldestJobDate": "2024-01-01T00:00:00Z",
"totalSizeBytes": 1048576,
"lastPrunedAt": "2024-02-01T03:00:00Z"
}POST /archive/prune
Delete archived jobs that finished before a cutoff, with their steps.
Request Body:
{
"olderThan": "30d",
"batchSize": 1000,
"maxBatches": 100
}olderThan is a duration ("30d", "12h", ...), an ISO date string, or a timestamp in milliseconds. batchSize and maxBatches are optional.
Response:
{
"deletedJobs": 250
}POST /archive/truncate
Delete every archived job and step. The body must confirm the request.
Request Body:
{
"confirm": true
}Response:
{
"success": true
}Config
GET /config
Get server configuration. This endpoint does not require authentication.
Response:
{
"authEnabled": true
}Actions
GET /actions
Get action statistics.
Response:
{
"actions": [
{
"name": "sendEmail",
"lastJobCreated": "2024-01-01T00:00:00Z",
"active": 2,
"completed": 95,
"failed": 3,
"cancelled": 0
}
]
}GET /actions/metadata
Get action metadata including input schemas and mock data.
Response:
[
{
"name": "sendEmail",
"mockInput": {
"to": "string",
"subject": "string",
"body": "string"
}
}
]POST /actions/:actionName/run
Run an action by creating a new job.
Request Body:
{
"to": "user@example.com",
"subject": "Hello",
"body": "Test"
}Response:
{
"success": true,
"jobId": "uuid"
}Error Handling
The server handles errors and returns appropriate status codes:
400- Validation error401- Unauthorized404- Not found500- Internal server error
Error Response Format:
{
"error": "Error type",
"message": "Error message"
}Authentication
Authentication is optional. When the login option is provided, all API endpoints (except /login and /refresh) require authentication via JWT tokens.
To authenticate, include the access token in the Authorization header:
Authorization: Bearer <accessToken>Token Management
The authentication system uses a two-token approach:
- Access Token: Short-lived token used for API requests (default:
'1h') - Refresh Token: Long-lived token used to obtain new access tokens (default:
'7d')
The protected endpoints accept only an access token: a refresh token in the Authorization header gets 401. POST /refresh accepts only a refresh token.
Token expiration times can be configured via:
login.expirationTime- Access token expiration (defaults to'1h')login.refreshTokenExpirationTime- Refresh token expiration (defaults to'7d')
Login
Get tokens by calling the POST /login endpoint with valid credentials:
{
"email": "user@example.com",
"password": "password123"
}Response:
{
"accessToken": "eyJ...",
"refreshToken": "eyJ..."
}Token Refresh
When the access token expires, use the POST /refresh endpoint to obtain a new access token:
{
"refreshToken": "eyJ..."
}Response:
{
"accessToken": "eyJ..."
}If login is not provided, all endpoints are publicly accessible without authentication.
Example: Full Server Setup
import { Elysia } from 'elysia'
import { createServer } from 'duron/server'
import { duron } from 'duron'
import { postgresAdapter } from 'duron/adapters/postgres'
// Create Duron client
const client = duron({
database: postgresAdapter({
connection: process.env.DATABASE_URL!,
}),
actions: {
sendEmail,
processOrder,
},
})
// Create API server
const api = createServer({
client,
prefix: '/api',
login: {
onLogin: async ({ email, password }) => {
// Your authentication logic
return await authenticateUser(email, password)
},
jwtSecret: process.env.JWT_SECRET!,
expirationTime: '1h', // Optional, defaults to '1h' (access token)
refreshTokenExpirationTime: '7d', // Optional, defaults to '7d' (refresh token)
},
})
// Create main app
const app = new Elysia().use(api).listen(3000)
console.log('Server running on http://localhost:3000')