open-index/open-npm huggingface dataset:
npm package: @psyqueue/dashboard
Description: > Web-based monitoring dashboard for PsyQueue. View queues, jobs, and system health.
Latest version: 0.1.0

# @psyqueue/dashboard

> Web-based monitoring dashboard for PsyQueue. View queues, jobs, and system health.

## Installation

```bash
npm install @psyqueue/dashboard
```

## Usage

```typescript
import { dashboard } from '@psyqueue/dashboard'

q.use(dashboard({
  port: 3001,
  auth: { type: 'bearer', credentials: 'my-secret' },
}))

await q.start()
// Dashboard at http://localhost:3001
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `port` | `number` | - | HTTP server port |
| `auth.type` | `'basic' \| 'bearer'` | - | Authentication type |
| `auth.credentials` | `string` | - | Secret token or `user:password` |

**Depends on:** `backend`

## Exports

- `dashboard(opts?)` -- Plugin factory
- `createDashboardServer(opts)` -- Standalone server factory

## Documentation

See [Observability Plugins](../../docs/plugins/observability.md#dashboard) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-audit-log
Description: > Tamper-evident, hash-chained audit trail for PsyQueue. Records every job lifecycle event.
Latest version: 0.1.0

# @psyqueue/plugin-audit-log

> Tamper-evident, hash-chained audit trail for PsyQueue. Records every job lifecycle event.

## Installation

```bash
npm install @psyqueue/plugin-audit-log
```

## Usage

```typescript
import { auditLog } from '@psyqueue/plugin-audit-log'

const plugin = auditLog({
  store: 'file',
  filePath: './audit.log',
  hashChain: true,
})
q.use(plugin)

// Query the audit log
const entries = plugin.audit.query({ event: 'job:completed', queue: 'orders' })

// Verify integrity
const valid = plugin.audit.verify()
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `store` | `'memory' \| 'file'` | *required* | Storage backend |
| `filePath` | `string` | - | Audit log file path (required for `'file'`) |
| `events` | `'all' \| string[]` | `'all'` | Events to record |
| `includePayload` | `boolean` | `false` | Include job payload |
| `hashChain` | `boolean` | `true` | Enable SHA-256 hash chain |
| `retention` | `string` | - | Retention metadata (e.g., `'90d'`) |

## Exports

- `auditLog(opts)` -- Plugin factory
- `computeHash`, `verifyChain` -- Hash chain utilities

## Documentation

See [Observability Plugins](../../docs/plugins/observability.md#audit-log) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-backpressure
Description: > Adaptive backpressure for PsyQueue. Automatically reduce throughput when the system is under pressure.
Latest version: 0.1.0

# @psyqueue/plugin-backpressure

> Adaptive backpressure for PsyQueue. Automatically reduce throughput when the system is under pressure.

## Installation

```bash
npm install @psyqueue/plugin-backpressure
```

## Usage

```typescript
import { backpressure } from '@psyqueue/plugin-backpressure'

q.use(backpressure({
  signals: {
    queueDepth: { pressure: 1000, critical: 5000 },
    errorRate: { pressure: 0.1, critical: 0.5 },
  },
  recovery: { cooldown: 30_000, stepUp: 2 },
}))
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `signals.queueDepth.pressure` | `number` | - | Queue depth threshold for PRESSURE |
| `signals.queueDepth.critical` | `number` | - | Queue depth threshold for CRITICAL |
| `signals.errorRate.pressure` | `number` | - | Error rate threshold (0-1) for PRESSURE |
| `signals.errorRate.critical` | `number` | - | Error rate threshold (0-1) for CRITICAL |
| `recovery.cooldown` | `number` | `0` | Cooldown before recovery (ms) |
| `recovery.stepUp` | `number` | `10` | Concurrency increase per recovery step |

## Exports

- `backpressure(opts)` -- Plugin factory
- `SignalMonitor` -- Signal monitoring class

## Documentation

See [Reliability Plugins](../../docs/plugins/reliability.md#backpressure) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-chaos
Description: > Chaos testing for PsyQueue. Inject controlled failures to validate resilience.
Latest version: 0.1.0

# @psyqueue/plugin-chaos

> Chaos testing for PsyQueue. Inject controlled failures to validate resilience.

## Installation

```bash
npm install @psyqueue/plugin-chaos
```

## Usage

```typescript
import { chaosMode } from '@psyqueue/plugin-chaos'

q.use(chaosMode({
  enabled: process.env.NODE_ENV !== 'production',
  scenarios: [
    { type: 'slowProcess', config: { probability: 0.3, minDelay: 500, maxDelay: 5000 } },
    { type: 'workerCrash', config: { probability: 0.1 } },
    { type: 'duplicateDelivery', config: { probability: 0.05 } },
  ],
}))
```

## Configuration

| Option | Type | Description |
|--------|------|-------------|
| `enabled` | `boolean` | Master switch |
| `scenarios` | `ChaosScenarioEntry[]` | List of scenarios |

### Scenarios

| Type | Config | Description |
|------|--------|-------------|
| `slowProcess` | `{ probability, minDelay, maxDelay }` | Random processing delays |
| `workerCrash` | `{ probability, message? }` | Simulated crashes |
| `duplicateDelivery` | `{ probability, extraRuns? }` | Test idempotency |

## Exports

- `chaosMode(opts)` -- Plugin factory
- `slowProcess`, `workerCrash`, `duplicateDelivery` -- Individual scenario middleware

## Documentation

See [Advanced Plugins](../../docs/plugins/advanced.md#chaos-testing) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-circuit-breaker
Description: > Circuit breaker pattern for PsyQueue. Protect downstream services from cascading failures.
Latest version: 0.1.0

# @psyqueue/plugin-circuit-breaker

> Circuit breaker pattern for PsyQueue. Protect downstream services from cascading failures.

## Installation

```bash
npm install @psyqueue/plugin-circuit-breaker
```

## Usage

```typescript
import { circuitBreaker } from '@psyqueue/plugin-circuit-breaker'

q.use(circuitBreaker({
  breakers: {
    'payment-api': {
      failureThreshold: 5,
      failureWindow: 30_000,
      resetTimeout: 60_000,
      halfOpenRequests: 3,
      onOpen: 'requeue',
    },
  },
}))

q.handle('payment.charge', async (ctx) => {
  return ctx.breaker('payment-api', async () => {
    return await chargePayment(ctx.job.payload)
  })
})
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `failureThreshold` | `number` | *required* | Failures to trip the breaker |
| `failureWindow` | `number` | *required* | Failure counting window (ms) |
| `resetTimeout` | `number` | *required* | Time before OPEN to HALF_OPEN (ms) |
| `halfOpenRequests` | `number` | *required* | Successes in HALF_OPEN to close |
| `onOpen` | `'requeue' \| 'fail'` | `'requeue'` | Action when circuit is open |

## Exports

- `circuitBreaker(opts)` -- Plugin factory
- `Breaker` -- Individual breaker class

## Documentation

See [Reliability Plugins](../../docs/plugins/reliability.md#circuit-breaker) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-crash-recovery
Description: > WAL-based crash recovery for PsyQueue. Automatically requeue orphaned jobs after a process crash.
Latest version: 0.1.0

# @psyqueue/plugin-crash-recovery

> WAL-based crash recovery for PsyQueue. Automatically requeue orphaned jobs after a process crash.

## Installation

```bash
npm install @psyqueue/plugin-crash-recovery
```

## Usage

```typescript
import { crashRecovery } from '@psyqueue/plugin-crash-recovery'

q.use(crashRecovery({
  walPath: './psyqueue.wal',
  autoRecover: true,
  onRecoverActiveJob: 'requeue',
}))
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `walPath` | `string` | `'./psyqueue.wal'` | Write-ahead log file path |
| `autoRecover` | `boolean` | `true` | Auto-recover on start |
| `onRecoverActiveJob` | `'requeue' \| 'fail' \| Function` | `'requeue'` | Recovery strategy |
| `shutdownTimeout` | `number` | `30000` | Max shutdown wait time (ms) |

**Depends on:** `backend`

## Exports

- `crashRecovery(opts?)` -- Plugin factory
- `WriteAheadLog` -- WAL class
- `recoverFromWal` -- Recovery function

## Documentation

See [Reliability Plugins](../../docs/plugins/reliability.md#crash-recovery) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-deadline-priority
Description: > Dynamic priority boosting for PsyQueue jobs approaching their deadlines.
Latest version: 0.1.0

# @psyqueue/plugin-deadline-priority

> Dynamic priority boosting for PsyQueue jobs approaching their deadlines.

## Installation

```bash
npm install @psyqueue/plugin-deadline-priority
```

## Usage

```typescript
import { deadlinePriority } from '@psyqueue/plugin-deadline-priority'

q.use(deadlinePriority({
  urgencyCurve: 'exponential',
  boostThreshold: 0.5,
  maxBoost: 95,
  interval: 5000,
  onDeadlineMiss: 'process-anyway',
}))

// Enqueue with a deadline
await q.enqueue('order.process', { orderId: '123' }, {
  priority: 5,
  deadline: new Date(Date.now() + 30 * 60 * 1000),
})
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `urgencyCurve` | `'linear' \| 'exponential' \| 'step' \| Function` | *required* | Priority scaling curve |
| `boostThreshold` | `number` | `0.5` | Start boosting at this fraction of time remaining |
| `maxBoost` | `number` | `95` | Maximum priority value |
| `interval` | `number` | `5000` | Recalculation interval (ms) |
| `onDeadlineMiss` | `'process-anyway' \| 'fail' \| 'move-to-dead-letter'` | `'process-anyway'` | Deadline miss action |

## Documentation

See [Scheduling Plugins](../../docs/plugins/scheduling.md#deadline-priority) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-exactly-once
Description: > Exactly-once delivery for PsyQueue via idempotency key deduplication.
Latest version: 0.1.0

# @psyqueue/plugin-exactly-once

> Exactly-once delivery for PsyQueue via idempotency key deduplication.

## Installation

```bash
npm install @psyqueue/plugin-exactly-once
```

## Usage

```typescript
import { exactlyOnce } from '@psyqueue/plugin-exactly-once'

q.use(exactlyOnce({ window: '24h', onDuplicate: 'ignore' }))

// First call: creates job
const id1 = await q.enqueue('task', data, { idempotencyKey: 'order-123' })

// Duplicate call: returns same ID, no new job
const id2 = await q.enqueue('task', data, { idempotencyKey: 'order-123' })
// id1 === id2
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `window` | `string` | `'24h'` | Dedup window (`'500ms'`, `'30s'`, `'5m'`, `'1h'`, `'7d'`) |
| `onDuplicate` | `'ignore' \| 'reject'` | `'ignore'` | Action on duplicate |
| `cleanupInterval` | `string` | `'1h'` | Expired key cleanup interval |

**Depends on:** `backend`

## Documentation

See [Reliability Plugins](../../docs/plugins/reliability.md#exactly-once-delivery) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-grpc-workers
Description: > gRPC worker transport for PsyQueue. Distribute job processing to remote workers over gRPC.
Latest version: 0.1.0

# @psyqueue/plugin-grpc-workers

> gRPC worker transport for PsyQueue. Distribute job processing to remote workers over gRPC.

## Installation

```bash
npm install @psyqueue/plugin-grpc-workers
```

## Usage

```typescript
import { grpcWorkers } from '@psyqueue/plugin-grpc-workers'

q.use(grpcWorkers({
  port: 50051,
  auth: true,
  tokens: ['worker-token-abc'],
  queues: ['email.send'],
}))
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `port` | `number` | *required* | gRPC server port |
| `auth` | `boolean` | - | Enable token authentication |
| `tokens` | `string[]` | - | Allowed worker tokens |
| `queues` | `string[]` | - | Restrict accessible queues |

## Exports

- `grpcWorkers(opts)` -- Plugin factory
- `GrpcWorkerServer` -- Server class

## Documentation

See [Transport Plugins](../../docs/plugins/transport.md#grpc-workers) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-http-workers
Description: > HTTP worker transport for PsyQueue. Distribute job processing to remote workers over HTTP.
Latest version: 0.1.0

# @psyqueue/plugin-http-workers

> HTTP worker transport for PsyQueue. Distribute job processing to remote workers over HTTP.

## Installation

```bash
npm install @psyqueue/plugin-http-workers
```

## Usage

```typescript
import { httpWorkers } from '@psyqueue/plugin-http-workers'

q.use(httpWorkers({
  port: 8080,
  auth: { type: 'bearer', tokens: ['worker-secret'] },
  queues: ['email.send'],
}))
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `port` | `number` | *required* | HTTP server port |
| `auth.type` | `'bearer'` | - | Authentication type |
| `auth.tokens` | `string[]` | - | Allowed bearer tokens |
| `queues` | `string[]` | - | Restrict accessible queues |

## Exports

- `httpWorkers(opts)` -- Plugin factory
- `HttpWorkerServer` -- Server class

## Documentation

See [Transport Plugins](../../docs/plugins/transport.md#http-workers) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-job-fusion
Description: > Job batching and fusion for PsyQueue. Combine similar jobs into a single fused job.
Latest version: 0.1.0

# @psyqueue/plugin-job-fusion

> Job batching and fusion for PsyQueue. Combine similar jobs into a single fused job.

## Installation

```bash
npm install @psyqueue/plugin-job-fusion
```

## Usage

```typescript
import { jobFusion } from '@psyqueue/plugin-job-fusion'

q.use(jobFusion({
  rules: [{
    match: 'notification.send',
    groupBy: (job) => (job.payload as any).userId,
    window: 5000,
    maxBatch: 50,
    fuse: (jobs) => ({
      userId: (jobs[0]!.payload as any).userId,
      messages: jobs.map(j => (j.payload as any).message),
    }),
  }],
}))
```

## Configuration

### FusionRule

| Field | Type | Description |
|-------|------|-------------|
| `match` | `string` | Job name to intercept |
| `groupBy` | `(job) => string` | Group key function |
| `window` | `number` | Batch window (ms) |
| `maxBatch` | `number` | Max jobs per batch |
| `fuse` | `(jobs) => unknown` | Merge payloads into one |

## Exports

- `jobFusion(opts)` -- Plugin factory
- `BatchCollector` -- Batch collector class

## Documentation

See [Advanced Plugins](../../docs/plugins/advanced.md#job-fusion) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-metrics
Description: > Prometheus metrics for PsyQueue. Tracks enqueued, completed, failed counts, processing duration, and queue depth.
Latest version: 0.1.0

# @psyqueue/plugin-metrics

> Prometheus metrics for PsyQueue. Tracks enqueued, completed, failed counts, processing duration, and queue depth.

## Installation

```bash
npm install @psyqueue/plugin-metrics prom-client
```

## Usage

```typescript
import { metrics } from '@psyqueue/plugin-metrics'

const plugin = metrics({ prefix: 'psyqueue' })
q.use(plugin)

// Expose metrics endpoint
const registry = plugin.getRegistry()
app.get('/metrics', async (req, res) => {
  res.set('Content-Type', registry.contentType)
  res.end(await registry.metrics())
})
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `prefix` | `string` | `'psyqueue'` | Metric name prefix |
| `defaultLabels` | `Record<string, string>` | - | Labels for all metrics |
| `registry` | `Registry` | `new Registry()` | Custom prom-client Registry |

## Exported Metrics

| Metric | Type | Labels |
|--------|------|--------|
| `{prefix}_jobs_enqueued_total` | Counter | `queue`, `name` |
| `{prefix}_jobs_completed_total` | Counter | `queue`, `name` |
| `{prefix}_jobs_failed_total` | Counter | `queue`, `name` |
| `{prefix}_job_duration_ms` | Histogram | `queue`, `name` |
| `{prefix}_queue_depth` | Gauge | `queue` |

## Documentation

See [Observability Plugins](../../docs/plugins/observability.md#prometheus-metrics) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-offline-sync
Description: > Local-first offline sync for PsyQueue. Buffer jobs locally when the remote backend is unreachable.
Latest version: 0.1.0

# @psyqueue/plugin-offline-sync

> Local-first offline sync for PsyQueue. Buffer jobs locally when the remote backend is unreachable.

## Installation

```bash
npm install @psyqueue/plugin-offline-sync
```

## Usage

```typescript
import { offlineSync } from '@psyqueue/plugin-offline-sync'

q.use(offlineSync({
  localPath: './local-queue.db',
  sync: { intervalMs: 30_000, autoSync: true },
  maxLocalJobs: 10_000,
}))
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `localPath` | `string` | *required* | Local SQLite buffer path |
| `sync.intervalMs` | `number` | - | Auto-sync interval (ms) |
| `sync.autoSync` | `boolean` | `true` | Enable background sync |
| `maxLocalJobs` | `number` | - | Max locally-buffered jobs |

## Events

| Event | When |
|-------|------|
| `offline:fallback` | Job buffered after remote failure |
| `offline:auto-synced` | Background sync completed |

## Exports

- `offlineSync(opts)` -- Plugin factory
- `SyncEngine` -- Sync engine class

## Documentation

See [Advanced Plugins](../../docs/plugins/advanced.md#offline-sync) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-otel-tracing
Description: > OpenTelemetry distributed tracing for PsyQueue. Trace context propagation from enqueue to process.
Latest version: 0.1.0

# @psyqueue/plugin-otel-tracing

> OpenTelemetry distributed tracing for PsyQueue. Trace context propagation from enqueue to process.

## Installation

```bash
npm install @psyqueue/plugin-otel-tracing @opentelemetry/api @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base
```

## Usage

```typescript
import { otelTracing } from '@psyqueue/plugin-otel-tracing'

q.use(otelTracing({
  serviceName: 'my-worker',
  exporter: 'console',
  traceEnqueue: true,
  traceProcess: true,
}))
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `serviceName` | `string` | *required* | OTel service name |
| `exporter` | `'console' \| 'memory'` | `'console'` | Span exporter |
| `traceEnqueue` | `boolean` | `true` | Trace enqueue operations |
| `traceProcess` | `boolean` | `true` | Trace process operations |
| `attributes` | `(job) => Record<string, string \| number>` | - | Custom span attributes |

## Documentation

See [Observability Plugins](../../docs/plugins/observability.md#opentelemetry-tracing) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-saga
Description: > Saga compensation for PsyQueue workflows. Automatic rollback when a workflow step fails.
Latest version: 0.1.0

# @psyqueue/plugin-saga

> Saga compensation for PsyQueue workflows. Automatic rollback when a workflow step fails.

## Installation

```bash
npm install @psyqueue/plugin-saga
```

## Usage

```typescript
import { saga } from '@psyqueue/plugin-saga'
import { workflows, workflow } from '@psyqueue/plugin-workflows'

q.use(workflows())
q.use(saga())

const def = workflow('payment')
  .step('reserve', reserveHandler, {
    compensate: async (ctx) => { await releaseReservation(ctx) },
  })
  .step('charge', chargeHandler, {
    after: 'reserve',
    compensate: async (ctx) => { await refundCharge(ctx) },
  })
  .build()
```

## Configuration

No configuration options. The plugin listens for `workflow:failed` events and runs compensations automatically.

**Depends on:** `workflows`

## How It Works

When a workflow step is dead-lettered, the saga plugin runs compensation handlers on all previously-completed steps in reverse completion order.

## Events

| Event | Data | When |
|-------|------|------|
| `workflow:compensating` | `{ workflowId, definitionName }` | Compensation starting |
| `workflow:compensated` | `{ workflowId, definitionName }` | All compensations succeeded |
| `workflow:compensation-failed` | `{ workflowId, definitionName }` | A compensation handler threw |

## Documentation

See [Workflow Plugins](../../docs/plugins/workflows.md#saga-compensation) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-scheduler
Description: > Delayed jobs and cron scheduling for PsyQueue.
Latest version: 0.1.0

# @psyqueue/plugin-scheduler

> Delayed jobs and cron scheduling for PsyQueue.

## Installation

```bash
npm install @psyqueue/plugin-scheduler
```

## Usage

```typescript
import { PsyQueue } from 'psyqueue'
import { sqlite } from '@psyqueue/backend-sqlite'
import { scheduler } from '@psyqueue/plugin-scheduler'

const q = new PsyQueue()
q.use(sqlite({ path: ':memory:' }))
q.use(scheduler({ pollInterval: 1000 }))

await q.start()

// Delayed job
await q.enqueue('task', {}, { runAt: new Date(Date.now() + 60_000) })

// Cron job
await q.enqueue('cleanup', {}, { cron: '0 2 * * *' })
```

## Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `pollInterval` | `number` | `1000` | Ms between polling for due scheduled jobs |
| `cronLockTtl` | `number` | `60000` | Lock TTL in ms for cron leader election |

**Depends on:** `backend`

## Exports

- `scheduler(opts?)` -- Plugin factory function
- `computeNextRunAt` -- Compute next cron occurrence

## Documentation

See [Scheduling Plugins](../../docs/plugins/scheduling.md) for detailed usage and configuration.

## License

MIT
npm package: @psyqueue/plugin-schema-versioning
Description: > Payload migration and Zod validation for PsyQueue. Evolve job schemas without breaking existing jobs.
Latest version: 0.1.0

# @psyqueue/plugin-schema-versioning

> Payload migration and Zod validation for PsyQueue. Evolve job schemas without breaking existing jobs.

## Installation

```bash
npm install @psyqueue/plugin-schema-versioning
```

## Usage

```typescript
import { schemaVersioning } from '@psyqueue/plugin-schema-versioning'
import { z } from 'zod'

q.use(schemaVersioning())

q.handle('email.send', schemaVersioning.versioned({
  current: 2,
  versions: {
    1: {
      schema: z.object({ to: z.string(), body: z.string() }),
      process: async (ctx) => { /* handle v1 */ },
      migrate: (payload) => ({ ...payload, subject: 'No Subject' }),
    },
    2: {
      schema: z.object({ to: z.string(), subject: z.string(), body: z.string() }),
      process: async (ctx) => { /* handle v2 */ },
    },
  },
}))
```

## Configuration

No plugin-level options. Versioning is configured per-handler via `schemaVersioning.versioned()`.

## Exports

- `schemaVersioning()` -- Plugin factory
- `schemaVersioning.versioned(config)` -- Create versioned handler
- `validatePayload` -- Validation utility

## Documentation

See [Advanced Plugins](../../docs/plugins/advanced.md#schema-versioning) for detailed usage.

## License

MIT
npm package: @psyqueue/plugin-tenancy
Description: > Multi-tenancy for PsyQueue. Per-tenant rate limits, tiered configuration, and fair scheduling.
Latest version: 0.1.0

# @psyqueue/plugin-tenancy

> Multi-tenancy for PsyQueue. Per-tenant rate limits, tiered configuration, and fair scheduling.

## Installation

```bash
npm install @psyqueue/plugin-tenancy
```

## Usage

```typescript
import { tenancy } from '@psyqueue/plugin-tenancy'

q.use(tenancy({
  tiers: {
    free: { rateLimit: { max: 100, window: '1m' }, concurrency: 2, weight: 1 },
    pro:  { rateLimit: { max: 1000, window: '1m' }, concurrency: 10, weight: 5 },
  },
  resolveTier: async (tenantId) => {
    const tenant = await db.tenants.findById(tenantId)
    return tenant.plan
  },
  scheduling: 'weighted-fair-queue',
}))

await q.enqueue('task', payload, { tenantId: 'tenant-123' })
```

## Configuration

| Option | Type | Description |
|--------|------|-------------|
| `tiers` | `Record<string, TierConfig>` | Tier definitions with rate limits, concurrency, and weights |
| `resolveTier` | `(tenantId: string) => Promise<string>` | Resolve tenant ID to tier name |
| `scheduling` | `'weighted-fair-queue' \| 'round-robin' \| 'strict-priority'` | Fair scheduling algorithm |

### TierConfig

| Field | Type | Description |
|-------|------|-------------|
| `rateLimit.max` | `number` | Max requests per window |
| `rateLimit.window` | `'1s' \| '1m' \| '1h'` | Sliding window duration |
| `concurrency` | `number` | Max concurrent jobs |
| `weight` | `number` | Scheduling weight |

**Depends on:** `backend`

## Exports

- `tenancy(opts)` -- Plugin factory
- `TierManager` -- Tier management class
- `SlidingWindowRateLimiter` -- Rate limiter
- `FairScheduler` -- Fair scheduling implementation

## Documentation

See [Multi-Tenancy Plugin](../../docs/plugins/tenancy.md) for detailed usage, scheduling modes, and real-world examples.

## License

MIT
npm package: @psyqueue/plugin-workflows
Description: > DAG-based workflow orchestration for PsyQueue. Define multi-step workflows with dependencies and conditional branching.
Latest version: 0.1.0

# @psyqueue/plugin-workflows

> DAG-based workflow orchestration for PsyQueue. Define multi-step workflows with dependencies and conditional branching.

## Installation

```bash
npm install @psyqueue/plugin-workflows
```

## Usage

```typescript
import { workflows, workflow } from '@psyqueue/plugin-workflows'

const q = new PsyQueue()
q.use(sqlite({ path: ':memory:' }))

const wf = workflows()
q.use(wf)

const def = workflow('order.process')
  .step('validate', async (ctx) => ({ valid: true }))
  .step('charge', async (ctx) => ({ chargeId: 'ch_123' }), { after: 'validate' })
  .step('ship', async (ctx) => ({ tracking: 'TRK-1' }), { after: 'charge' })
  .build()

wf.engine.registerDefinition(def)

await q.start()
const workflowId = await q.enqueue('order.process', { items: ['widget'] })
```

## Configuration

The `workflows()` factory takes no options. Configure by registering workflow definitions.

**Depends on:** `backend`

## Step Options

| Option | Type | Description |
|--------|------|-------------|
| `after` | `string \| string[]` | Step dependencies |
| `when` | `(ctx) => boolean` | Conditional execution |
| `compensate` | `JobHandler` | Saga compensation handler |

## Exports

- `workflows()` -- Plugin factory
- `workflow(name)` -- Workflow builder factory
- `WorkflowBuilder` -- Builder class
- `WorkflowEngine` -- Engine class
- `WorkflowStore` -- State store

## Documentation

See [Workflow Plugins](../../docs/plugins/workflows.md) for detailed usage, parallel execution, and conditional branching.

## License

MIT